1

I am trying to wrap my head around parameter sets. It seems fairly straight forward up until the point where you need to be able to use A or B, or both A & B. I need to essentially be able to say that out of two parameters, at least one must be provided.

This is an example of the code that I am currently using (without parameter sets), but this would allow for nothing but $c to be passed.

Function Test-Params
{
    Param
    (
        [string[]]
        $a,
        [string[]]
        $b,
        [Parameter(Mandatory=$true)]
        [string]
        $c
    )
}

Is there a way to handle this with parameter sets, or is it more appropriate to perform some form of validation within the function?

I would like for the following to be accepted:

Test-Params -a $arr_a -c "C:\test.txt"
Test-Params -b $arr_b -c "C:\test.txt"
Test-Params -a $arr_a -b $arr_b -c "C:\test.txt"

1 Answer 1

2

Define multiple Parameter Sets (blog on this) for each option you want to be accepted:

Function Test-Params {
    Param (
        [Parameter(ParameterSetName='AC', Mandatory=$True)]
        [Parameter(ParameterSetName='ABC', Mandatory=$True)]
        [string[]]$a,

        [Parameter(ParameterSetName='BC', Mandatory=$True)]
        [Parameter(ParameterSetName='ABC', Mandatory=$True)]
        [string[]]$b,

        [Parameter(ParameterSetName='AC', Mandatory=$True)]
        [Parameter(ParameterSetName='BC', Mandatory=$True)]
        [Parameter(ParameterSetName='ABC', Mandatory=$True)]
        [string]$c
    )

    $a
    $b
    $c
}

These will be accepted:

Test-Params -a ParamA -c ParamC
Test-Params -b ParamB -c ParamC
Test-Params -a ParamA -b ParamB -c ParamC

But if you try just A & B, it will use ParameterSetName='ABC' and prompt for C as this is also mandatory in that set.

C:\> Test-Params -a ParamA -b ParamB
cmdlet Test-Params at command pipeline position 1
Supply values for the following parameters:
c: 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.