Home > Enterprise >  PowerShell ParameterSet Groups
PowerShell ParameterSet Groups

Time:10-14

My function has two groups of parameters (A, B), where only one parameter may be used within the group (A1 or A2, B1 or B2), both or only one group may be used. For demonstration I have the following code.

Function Test-1{

    Param(
        [Parameter(ParameterSetName="A1B1")]
        [Parameter(ParameterSetName="A1B2")]
        [switch]$A1,

        [Parameter(ParameterSetName="A2B1")]
        [Parameter(ParameterSetName="A2B2")]
        [switch]$A2,

        [Parameter(ParameterSetName="A1B1")]
        [Parameter(ParameterSetName="A2B1")]
        [switch]$B1,

        [Parameter(ParameterSetName="A1B2")]
        [Parameter(ParameterSetName="A2B2")]
        [switch]$B2
    )

    Write-Output "OK"

}

Allowed:

Test-1 -A1
Test-1 -A2
Test-1 -B1
Test-1 -B2
Test-1 -A1 -B1
Test-1 -A1 -B2
Test-1 -A2 -B2
Test-1 -A2 -B1

Not allowed:

Test-1 -A1 -A2
Test-1 -B1 -B2
Test-1 -A1 -B1 -B2
Test-1 -A2 -B1 -B2
Test-1 -A1 -A2 -B1
Test-1 -A1 -A2 -B2
Test-1 -A1 -A2 -B1 -B2

This works:

Test-1 -A1 -B1
Test-1 -A1 -B2
Test-1 -A2 -B2
Test-1 -A2 -B1

This fails "parameter set cannot be resolved using the specified named parameters":

Test-1 -A1
Test-1 -A2
Test-1 -B1
Test-1 -B2

How can I achieve my goal?

CodePudding user response:

This can be done, but obviously gets more complicated when number of parameter combinations increase:

Function Test-1{

    Param(
        [Parameter(Mandatory=$True, ParameterSetName="A1B1")]
        [Parameter(Mandatory=$True, ParameterSetName="A1B2")]
        [Parameter(Mandatory=$True, ParameterSetName="A1")]
        [switch]$A1,

        [Parameter(Mandatory=$True, ParameterSetName="A2B1")]
        [Parameter(Mandatory=$True, ParameterSetName="A2B2")]
        [Parameter(Mandatory=$True, ParameterSetName="A2")]
        [switch]$A2,

        [Parameter(Mandatory=$True, ParameterSetName="A1B1")]
        [Parameter(Mandatory=$True, ParameterSetName="A2B1")]
        [Parameter(Mandatory=$True, ParameterSetName="B1")]
        [switch]$B1,

        [Parameter(Mandatory=$True, ParameterSetName="A1B2")]
        [Parameter(Mandatory=$True, ParameterSetName="A2B2")]
        [Parameter(Mandatory=$True, ParameterSetName="B2")]
        [switch]$B2
    )

    Write-Output "OK - $($PsCmdlet.ParameterSetName)"
}

I added separate sets for single parameters, as without them powershell couldn't resolve between A1B1 and A1B2 sets when only using -A1 parameter. Mandatory clauses are needed too, because still it wouldn't know if -A1 means A1 set, or one of A1B1/A1B2 sets with optional B1/B2 parameter.

Now all scenarios work as expected. $PsCmdlet.ParameterSetName in output is useful for initial testing.

  • Related