Is there a way to have PowerShell enforce mutually exclusive parameters if there is more than one group (of mutually exclusive parameters)?
For example, consider these parameters in script Test.ps1 (all are optional and non-positional):
Param(
# GROUP A (a1 and a2 are mutually exclusive)
[switch]$a1,
[switch]$a2,
# GROUP B (b1 and b2 are mutually exclusive)
[switch]$b1,
[switch]$b2
)
Is there a way to enforce that at most one parameter from group A (i.e. $a1 or $a2) and/or at most one parameter from group B (i.e. $b1 or $b2) are specified?
The following calls would be valid:
.\Test.ps1
.\Test.ps1 -a1
.\Test.ps1 -a2
.\Test.ps1 -b1
.\Test.ps1 -b2
.\Test.ps1 -a1 -b1
.\Test.ps1 -a1 -b2
.\Test.ps1 -a2 -b1
.\Test.ps1 -a2 -b2
The following calls would be invalid:
.\Test.ps1 -a1 -a2 -b1 -b2
.\Test.ps1 -a1 -b1 -b2
.\Test.ps1 -a2 -b1 -b2
.\Test.ps1 -a1 -a2 -b1
.\Test.ps1 -a1 -a2 -b2
I know how to use ParameterSetName to enforce a single group of mutually exclusive parameters, but I cannot figure out how to enforce multiple groups. Not even sure if it is possible at all. Notice that the real example is more complex than the sample above (each group has more than one parameter and they are not all switches).
UPDATE: From the recommendation in a comment, I added parameter sets:
Param(
# GROUP A (a1 and a2 are mutually exclusive)
[Parameter(ParameterSetName="a1")]
[Parameter(ParameterSetName="b1")]
[Parameter(ParameterSetName="b2")]
[switch]$a1,
[Parameter(ParameterSetName="a2")]
[Parameter(ParameterSetName="b1")]
[Parameter(ParameterSetName="b2")]
[switch]$a2,
# GROUP B (b1 and b2 are mutually exclusive)
[Parameter(ParameterSetName="a1")]
[Parameter(ParameterSetName="a2")]
[Parameter(ParameterSetName="b1")]
[switch]$b1,
[Parameter(ParameterSetName="a1")]
[Parameter(ParameterSetName="a2")]
[Parameter(ParameterSetName="b2")]
[switch]$b2
)
This does not seem to do what I need it to do:
PS D:\Scripts> Get-Help .\Test.ps1 Test.ps1 [-a1] [-a2] [-b2] [<CommonParameters>] Test.ps1 [-a1] [-a2] [-b1] [<CommonParameters>] Test.ps1 [-a1] [-b1] [-b2] [<CommonParameters>] Test.ps1 [-a2] [-b1] [-b2] [<CommonParameters>]