powershellparametersparameter-sets

How can I have a default parameter set in Powershell that doesn't require a parameter value?


I'm trying to be able to call the parameter 'help' as a default without the code prompting for a parameter value and without implicitly having to type '-help' and when I do that, it fails as shown in the image below. I'm not sure what the parameter set syntax should be, how can I achieve this?

To duplicate the error, save the snippet of code below as testing.ps1 and call .\testing.ps1 from the directory it's saved in.

[CmdletBinding(DefaultParameterSetName='Help')]
Param(
    [Parameter(ParameterSetName='Add', Mandatory=$true)]
    [Switch]$Add,

    [Parameter(ParameterSetName='Remove', Mandatory=$true)]
    [Switch]$Remove,

    [Parameter(ParameterSetName='Help', Mandatory=$true)]
    [Switch]$Help,

    [Parameter(ParameterSetName='Add', Mandatory=$true)]
    [Parameter(ParameterSetName='Remove', Mandatory=$true)]
    [Parameter(ParameterSetName='Help', Mandatory=$false)]
    [String]$UserID
)


switch ($PSCmdlet.ParameterSetName) {
    'Add'    { Write-Host "You chose Add"; }
    'Remove' { Write-Host "You chose Remove"; }
    'Help'   { Write-Host "You chose Help"; }
}

enter image description here


Solution

  • The user is prompted because you've marked the $Help parameter Mandatory in association with the default parameter set.

    As a general rule of thumb I'd recommend avoiding user-defined parameters like $Help since PowerShell already has a comprehensive help content subsystem you can query using <command> -? or Get-Help <command>

    Thus, my suggestion would be to remove the user-defined $Help parameter entirely, which solves the problem:

    [CmdletBinding(DefaultParameterSetName='Help')]
    Param(
        [Parameter(ParameterSetName='Add', Mandatory=$true)]
        [Switch]$Add,
    
        [Parameter(ParameterSetName='Remove', Mandatory=$true)]
        [Switch]$Remove,
    
        [Parameter(ParameterSetName='Add', Mandatory=$true)]
        [Parameter(ParameterSetName='Remove', Mandatory=$true)]
        [Parameter(ParameterSetName='Help', Mandatory=$false)]
        [String]$UserID
    )
    
    switch ($PSCmdlet.ParameterSetName) {
        'Add'    { Write-Host "You chose Add"; }
        'Remove' { Write-Host "You chose Remove"; }
        'Help'   { Write-Host "You chose Help"; }
    }
    

    If you insist on declaring the $Help parameter yourself, simply make sure it's not marked mandatory:

    [Parameter(ParameterSetName='Help', Mandatory=$false)]
    [Switch]$Help,