powershellparameter-sets

Powershell - Multiple Sets of Parameter Sets


Consider these parameters:

        [parameter(Mandatory = $true)]
        [string[]]$UserId,

        [parameter(Mandatory = $true)]
        [string[]]$EmployeeId,

        [parameter(Mandatory = $true)]
        [string[]]$GroupId,

        [parameter(Mandatory = $true)]
        [string[]]$GroupName

All of them are mandatory; read: At least one of, UserId or EmployeeId; At least one of, GroupId or GroupName.

Another way to look at it; A & B are mutually exclusive; C & D are mutually exclusive


Possible Combinations I want:

I have tried to use multiple parameter sets to accomplish this but I am clearly not doing something correctly. I can't seem to work out the correct combination of parameter sets. I did see several example posts on this topic and tried to apply it to this use case; I was not successful.


Solution

  • The list of "possible combinations" is your list of parameter sets - now you just need to apply them to each relevant parameter:

    function Test-ParamSet {
        param(
            [Parameter(Mandatory = $true, ParameterSetName = 'UserIdGroupId')]
            [Parameter(Mandatory = $true, ParameterSetName = 'UserIdGroupName')]
            [string[]]$UserId,
    
            [Parameter(Mandatory = $true, ParameterSetName = 'EmployeeIdGroupId')]
            [Parameter(Mandatory = $true, ParameterSetName = 'EmployeeIdGroupName')]
            [string[]]$EmployeeId,
    
            [Parameter(Mandatory = $true, ParameterSetName = 'UserIdGroupId')]
            [Parameter(Mandatory = $true, ParameterSetName = 'EmployeeIdGroupId')]
            [string[]]$GroupId,
    
            [Parameter(Mandatory = $true, ParameterSetName = 'UserIdGroupName')]
            [Parameter(Mandatory = $true, ParameterSetName = 'EmployeeIdGroupName')]
            [string[]]$GroupName
        )
    
        $PSCmdlet.ParameterSetName
    }
    

    Resulting in the following parameter set resolution behavior:

    PS ~> Test-ParamSet -UserId abc -GroupId 123
    UserIdGroupId
    PS ~> Test-ParamSet -UserId abc -GroupName 123
    UserIdGroupName
    PS ~> Test-ParamSet -EmployeeId abc -GroupId 123
    EmployeeIdGroupId
    PS ~> Test-ParamSet -EmployeeId abc -GroupName 123
    EmployeeIdGroupName