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.