Default ParameterSetName

  • Context:

Let’s say you use an advanced feature – ParameterSetName – in your PowerShell code.

Let’s say you don’t specify a default ParameterSetName in the CmdletBinding and that some parameters don’t have an explicitly defined ParameterSetName.

What’s the name of the parameterset in this case?

  • Hands-on!

Here’s a sample code I propose to discover it.

Function Test-Param {
[CmdletBinding(DefaultParameterSetName='Set1')]
Param(
[Parameter(ParameterSetName = 'Set1')]
[switch]$Param1,
[Parameter(ParameterSetName = 'Set2')]
[switch]$Param2,
[switch]$Common
)
Begin {}
Process {
    Switch ($PSCmdlet.ParameterSetName) {
        'Set1' {
            $PSCmdlet.ParameterSetName
            break
        }
        'Set2' {
            $PSCmdlet.ParameterSetName
            break
        }
        default {
            $PSCmdlet.ParameterSetName
        }
    }
}
End {}
}

Let’s execute some code and see what we can uncover:

# Execute the function to see that it works
Test-Param

# Check the DefaultParameterSetName specified in the CmdletBinding
(gcm Test-Param).DefaultParameterSet

# Get the properties of the first parameter of the function
(gcm Test-Param).Parameters['Param1']

As you know gcm is the alias for Get-Command.

Everything looks good and is expected so far.
Now, let’s have a look at the 3rd parameter that doesn’t have any ParameterSetName defined

(gcm Test-Param).Parameters['Common']

Got it. It seems that when there’s no ParameterSetName defined, its name is: __AllParameterSets

Let’s say, I change the above function and omit the DefaultParameterSetName in the CmdletBinding:

At runtime, there’s an error thrown saying that the parameterSet is ambiguous.
Get-Command is still able to see the syntax although the function will fail at runtime.

Let’s use the default parameter name __AllParameterSets instead of Set1 and compare the syntax of the functions

Set1 syntax:

Set1

__AllParameterSets syntax:

__AllParameterSets
  • Conclusion

Using the default parameter name __AllParameterSets gives us a 3rd way to execute with the Common parameter alone. That parameter is valid and used as well by the 2 other ParameterSetNames I specified in the Param block.

Nice and subtle. PowerShell rock 😎

Advertisement

1 thought on “Default ParameterSetName

  1. Pingback: Dew Drop – February 1, 2022 (#3611) – Morning Dew by Alvin Ashcraft

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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