Add a Parameter to Multiple Parameter Sets in PowerShell

A colleague asked the question of whether a parameter function could belong to multiple parameter sets, but not all of them, say in Set A and B, but not C. So I tried a couple of things out, then checked the documentation to see what was actually possible.

It states

“Each parameter set must have a unique parameter that the Windows PowerShell runtime can use to expose the appropriate parameter set.”

i.e. each parameter set distinguishes itself by means of a unique parameter, but that doesn’t imply that another parameter couldn’t be in multiple sets, but not all of them.

Further down is stated

“For parameters that belong to multiple parameter sets, add a Parameter attribute for each parameter set.”

So the following example illustrates the syntax required to make parameter D part of Set 1 and Set 2, parameter E part of Set 2 and Set 3, and parameter F in Set 1, 2 and 3.


function Test-Param{ <# .SYNOPSIS Test-Param

.DESCRIPTION Test-Param

.PARAMETER A A

.PARAMETER B B

.PARAMETER C C

.PARAMETER D D

.PARAMETER E E

.PARAMETER F F

.EXAMPLE C:\\PS> Test-Param -A "Anne" -D "Dave" -F "Freddy" #> \[CmdletBinding()\]

param (

\[parameter(Mandatory=$true,ParameterSetName = "Set 1")\] \[ValidateNotNullOrEmpty()\] \[String\]$A,

\[parameter(Mandatory=$true,ParameterSetName = "Set 2")\] \[ValidateNotNullOrEmpty()\] \[String\]$B,

\[parameter(Mandatory=$true,ParameterSetName = "Set 3")\] \[ValidateNotNullOrEmpty()\] \[String\]$C,

\[parameter(Mandatory=$false,ParameterSetName = "Set 1")\] \[parameter(ParameterSetName = "Set 2")\] \[ValidateNotNullOrEmpty()\] \[String\]$D,

\[parameter(Mandatory=$false,ParameterSetName = "Set 2")\] \[parameter(ParameterSetName = "Set 3")\] \[ValidateNotNullOrEmpty()\] \[String\]$E,

\[parameter(Mandatory=$false)\] \[ValidateNotNullOrEmpty()\] \[String\]$F )

&nbsp;

}

&nbsp;

Looking at the help confirms how the Parameter Sets are organised: