PowerShell for Windows Admins

Jul 23 2014   2:10PM GMT

Its mandatory Jim but not as we know it

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

A uestion was asked on the forum about whether a parameter could be made mandatory sometimes and nor other – in particular if a parameter could be made mandatory if another parameter was used.

My initial thought was that it couldn’t but a little experimentation with parameter sets produced this:

function test {

[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$Param1,

[Parameter(Mandatory)]
[string]$Param2,

[Parameter(ParameterSetName = ‘Set1′)]
[switch]$Param3,

[Parameter(ParameterSetName = ‘Set1′,Mandatory)]
[Parameter(ParameterSetName = ‘Set2′)]
[string]$Param4,

[Parameter(ParameterSetName = ‘Set2′)]
[switch]$param5
)

“parameters accepted”

}

The function doesn’t do anything – its just to demonstrate the parameters

So this works:

£> test -Param1 x -Param2 y
parameters accepted

These work

£> test -Param1 x -Param2 y -param5
parameters accepted

£> test -Param1 x -Param2 y -param5 -Param4 z
parameters accepted

So you see that param4 when used in parameter set set2 is not mandatory

However,

£> test -Param1 x -Param2 y -param3
cmdlet test at command pipeline position 1
Supply values for the following parameters:
Param4: a
parameters accepted

So when you use parameter 3 you’re in parameter set set1 and param4 becomes mandatory.

Bit messy with the parameter decorators but it gets the job done

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: