cogumel0
cogumel0

Reputation: 2661

Multiple Mandatory Parameter Sets

I am working on a function that contains multiple parameter sets, with some being mandatory and some optional.

This is just an example, but imagine the following situation:

A function to add or remove either a user or a computer from an AD group (where for some reason you need to distinguish between users and computers).

Please remember this is just an example. In this case it would be far easier to make add/remove a single [string] parameter with a ValidateSet(), but that is beside the point.

So you have 4 parameter sets:

Param
(
    [Parameter(ParameterSetName = 'Add', Mandatory = $true)][switch] $Add,
    [Parameter(ParameterSetName = 'Remove', Mandatory = $true)][switch] $Remove,

    [Parameter(ParameterSetName = 'User', Mandatory = $true)][switch] $User,
    [Parameter(ParameterSetName = 'Computer', Mandatory = $true)][switch] $Computer
)

The problem now is that you can only use one of the four parameters, rather than (Add or Remove) and (User or Computer)

I know it's possible to use multiple parameter sets per parameter, but I can't see a way of forcing it to have two parameters sets which are always mandatory. Effectively you must always specify either Add or Remove and also either User or Computer.

How can this be done?

Upvotes: 1

Views: 634

Answers (1)

ravikanth
ravikanth

Reputation: 25810

You need multiple parameter sets defined for these different combinations. Try this:

Function TestParamSet {
    [CmdletBinding()]
    Param
    (
        [Parameter(ParameterSetName = 'AddUser', Mandatory = $true)]
        [Parameter(ParameterSetName = 'AddComputer', Mandatory = $true)]
        [switch] $Add,

        [Parameter(ParameterSetName = 'RemoveUser', Mandatory = $true)]
        [Parameter(ParameterSetName = 'RemoveComputer', Mandatory = $true)]
        [switch] $Remove,

        [Parameter(ParameterSetName = 'AddUser', Mandatory = $true)]
        [Parameter(ParameterSetName = 'RemoveUser', Mandatory = $true)]
        [switch] $User,

        [Parameter(ParameterSetName = 'AddComputer', Mandatory = $true)]
        [Parameter(ParameterSetName = 'RemoveComputer', Mandatory = $true)]
        [switch] $Computer
    )

    Process {
        #Do Nothing
    }
}

And, this is what you see when you get help on this function:

PS C:\> Get-Help TestParamSet 

NAME
    TestParamSet

SYNTAX
    TestParamSet -Add -Computer  [<CommonParameters>]

    TestParamSet -Add -User  [<CommonParameters>]

    TestParamSet -Remove -Computer  [<CommonParameters>]

    TestParamSet -Remove -User  [<CommonParameters>]


ALIASES
    None


REMARKS
    None

Upvotes: 3

Related Questions