How to configure a function parameter to belong to multiple parameter sets

A question turned up recently regarding how a function parameter can be configured to belong to multiple parameter sets. Before I get to the answer, let us define what a parameter set is. This is a quote from the “Cmdlet Parameter Sets” documentation on MSDN:

Windows PowerShell uses the concept of parameter sets to enable you to write a single cmdlet that can perform different actions for different scenarios. Parameter sets allow you to expose different parameters to the user and to return different information based on the parameters specified by the user.

You can also read an introduction blog post on the PowerShell team blog about parameter sets, as well as a practical example on the Hey, Scripting Guy! blog.

To explain what we want to accomplish, lets look at an example:

image

In the above example a function named “myfunction” is defined with two different parameter sets, “1” and “2”.

Note: I am using the Intellisense feature of the new Windows PowerShell ISE 3.0 to show the available parameters.

Here we can see that initially all the 4 defined parameters is available:

image

As soon as we choose a parameter belonging to a parameter set, the corresponding parameter set is enabled and only other parameters from the same set is available:

image

Here we can see the same behavior, where parameter set “2” is enabled:

image

Back to the original question, we want to make a parameter available on several parameter sets. My initial response was that not defining a parameter set would make the parameter available on all parameter sets, as stated in the MSDN documentation:
"If no parameter set is specified for a parameter, the parameter belongs to all parameter sets."

To see how this works we define an additional parameter named “e”, where we do not define any parameter attributes:

image

Here we can see that even if a parameter from parameter set “1” is enabled, our new parameter “e” is available:

image

The same is true if we use the other parameter set:

image

What I didnt know is what fellow PowerShell MVP Steven Murawski pointed out:

The other option is to annotate it with a parameter attribute for each parameter set it belongs to, in case it does not belong to all parameter sets.

To see how this work we add a third parameter set, and add the last parameter “g” to parameter set “1” and “2” only:

image

Here we can see that parameter “g” is available on parameter set “1” and “2”, but not on “3”:

image

image

image

To conclude, we have the flexibility to both add a parameter to all parameter sets, and to explicitly define a parameter on multiple parameter sets.