Adding Multiple Parameter Sets to a PowerShell Function

Sometimes you need to add more than one parameter set to a function you’re creating. If that’s not something you’re familiar with, it can be a little confusing at first. In the following example, I want to either specify the Name or Module parameter, but not both at the same time. I also want the Path parameter to be available when using either of the parameter sets.

Taking a look at the syntax shows the function shown in the previous example does indeed have two different parameter sets and the Path parameter exists in both of them. The only problem is both the Name and Module parameters are mandatory and it would be nice to have Name available positionally.

Simply specifying Name as being in position zero solves that problem.

Notice that “Name” is now enclosed in square brackets when viewing the syntax for the function. This means that it’s a positional parameter and specifying the parameter name is not required as long as its value is specified in the correct position. Keep in mind that you should always use full command and parameter names in any code that you share.

While continuing to work on the parameters for this function, I decided to make the Path parameter available positionally as well as adding pipeline input support for it. I’ve seen others add those requirements similar to what’s shown in the following example.

This might initially seem to work, but what appears to happen is that it ignores the Parameter blocks for both the Name and Module parameter set names for the Path parameter because they are effectively blank. This is because another totally separate parameter block is specified for the Path parameter. Looking at the help for the Path parameter shows that it accepts pipeline input, but looking at the individual parameter sets seems to suggest that it doesn’t. It’s confused to say the least.

There’s honestly no reason to specify the individual parameter sets for the Path parameter if all of the options are going to be the same for all of the parameter sets.

Removing those two empty parameter declarations above the Path parameter that reference the individual parameter sets clears up the problems.

If you want to specify different options for the Path parameter to be used in different parameter sets, then you would need to explicitly specify those options as shown in the following example. To demonstrate this, I’ve omitted pipeline input by property name when the Module parameter set is used.

Now everything looks correct.

For more information about using multiple parameter sets in your functions, see the about_Functions_Advanced_Parameters help topic.


Leave a Reply

%d bloggers like this: