vdenotaris
vdenotaris

Reputation: 13637

Powershell: multi-parameters validation

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?

Upvotes: 1

Views: 1477

Answers (1)

user2226112
user2226112

Reputation:

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.

Upvotes: 2

Related Questions