PowerShell Function: make a Parameter dependent of the Value of another Parameter

I had the case where I needed to make sure that one switch parameter of a PowerShell function can only be used, if another parameter had a certain value.
For example: the switch parameter -MYSWITCH can only be used if the value of the parameter -Selection is set to “POSSIBLE”.

The following PowerShell function is written to do exactly that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function myFunction() {
 
    [cmdletbinding(
        DefaultParameterSetName='Default'
    )]
    Param
    (
        [Parameter()]
        [String]$Selection,
 
        [Parameter(ParameterSetName='Selection')]
        [ValidateScript({ $Selection -eq 'POSSIBLE' })]
        [Switch]$MYSWITCH
    )
 
    # Print out current ParameterSet Selection
    $PSCmdlet.ParameterSetName
}
 
# Selection is POSSIBLE and therefore, the -MYSWITCH switch is allowed
myFunction -Selection POSSIBLE -MYSWITCH 
 
# Selection is IMPOSSIBLE and therefore, the -MYSWITCH switch is NOT allowed => throws an error
myFunction -Selection IMPOSSIBLE -MYSWITCH
 
# Selection is IMPOSSIBLE and therefore, the -MYSWITCH switch is NOT allowed => works well because -MYSWITCH is not used
myFunction -Selection IMPOSSIBLE

If the -Selection is set to anything different then “POSSIBLE”, using the switch -MYSWITCH just throws an error. This is the expected behavior in that case.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.