Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Parameter Sets: Require either A or B to be set

Is there a simple way to have a parameter set that allows either A or B but not both to be specified?

E.G. My script will either accept:

.\SimpleScript.ps1 -A "str1" -X 1 -Y 2 -Z 3

or

.\SimpleScript.ps1 -B "str2" -X 1 -Y 2 -Z 3

but not:

.\SimpleScript.ps1 -A "str1" -B "str2" -X 1 -Y 2 -Z 3
like image 528
Dech Avatar asked Jul 25 '17 12:07

Dech


2 Answers

You can write a CmdLet and use Parameter sets.

Have a look to the base documentation at About Functions Advanced Parameters

Param
(
    [parameter(Mandatory=$true,
    ParameterSetName="WithA")]
    [String]
    $A,

    [parameter(Mandatory=$true,
    ParameterSetName="WithB")]
    [String]
    $B,

    [parameter(Mandatory=$true)]
    [Int]
    $X
...
)
like image 172
JPBlanc Avatar answered Oct 13 '22 20:10

JPBlanc


You want to use Parameter Sets. By making -A a mandatory parameter in one parameter set and -B mandatory in a different parameter set, supplying both -A and -B will cause PowerShell to be unable to resolve which parameter set you intended, and reject the command (with an error indicating that it couldn't resolve the parameter set). Look at this Scripting Guy column for an example.

like image 42
Jeff Zeitlin Avatar answered Oct 13 '22 18:10

Jeff Zeitlin