1

I've a Powershell function as follows:

function myfunct {

    param(
        [Parameter(ParameterSetName="p1")]
        [string] $p1,
        [Parameter(ParameterSetName="p21")]
        [string] $p21,
        [Parameter(ParameterSetName="p22")]
        [string] $p22
    )

    # ...

}

This script accepts two configurations of parameters:

  1. By specifying the value of p1 : p1 and [not (p21 and p22)]

  2. By specifying the value of p21 and p22 : (not p1) and (p21 and p22)

Now, I would like to check their mutual exclusivity. By reading the article PowerShell V2: ParameterSets on MSDN, I found an example about how to properly use the value of $PsCmdlet.ParameterSetName in order to check the specified parameter:

function test-param 
{ 
param( 
[Parameter(ParameterSetName="p1",Position=0)] 
[DateTime] 
$d, 

[Parameter(ParameterSetName="p2", Position=0)] 
[int] 
$i 
) 
    switch ($PsCmdlet.ParameterSetName) 
    { 
    "p1"  { Write-Host $d; break} 
    "p2"  { Write-Host $i; break} 
    } 
}

According to the the example above, $PsCmdlet.ParameterSetName returns the value of a single parameter, but in my second configuration I need to know if p21 and p22 have been inserted (and if p1 is empty, of course).

Is there a way to perform the parameter validation as desired? If yes, how?

5
  • You created three parameter sets but it looks like you meant to create only two. Commented Mar 9, 2015 at 10:41
  • I would like to create two configurations, but the second one needs two parameters. Commented Mar 9, 2015 at 10:42
  • Yes, what's the issue? Call the sets "p1" and "p2" or whatever. Add two parameters to the second parameter set. Commented Mar 9, 2015 at 10:44
  • Do you talking about something like that: myscript -conf2 p21value p22value? Commented Mar 9, 2015 at 10:45
  • 1
    I'll make an example... Commented Mar 9, 2015 at 10:54

1 Answer 1

2
function Test(
    [Parameter(ParameterSetName="ID")] [int]$ID,
    [Parameter(ParameterSetName="Name")] [string]$Name,
    [Parameter(ParameterSetName="Name")] [string]$Path
) {
    switch ($PsCmdlet.ParameterSetName) {
        'ID' {
            "ID: $ID"
        }
        'Name' {
            "Name: $Name    Path: $Path"
        }
    }
}

You can additionally make some parameters mandatory with Mandatory=$true if you want.

There is no need to check the "mutual exclusivity". PowerShell does that for you - that's why you are defining parameter sets in the first place.

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.