Igor ostrovsky
Igor ostrovsky

Reputation: 7392

Powershell script parameters: display help on incorrect usage?

In Powershell V2, I am trying to use the Param() declaration to parse the switches passed into a script. My problem can be illustrated using this script (example.ps1):

Param(
    [switch] $A,
    [switch] $B,
    [switch] $C
)
echo "$A, $B, $C"

My problem is that this script will silently ignore any incorrect switches. For instance, "example.ps1 -asdf" will just print "False, False, False", instead of reporting the incorrect usage to the user.

I noticed that the behavior changes if I add a positional parameter:

Param(
    [switch] $A,
    [switch] $B,
    [switch] $C,
    [parameter(position=0)] $PositionalParameter
)
echo "A:$A, B:$B, C:$C"

Now, a ParameterBindingException will be raised if I run "example2.ps1 -asdf". But, "example2.ps1 asdf" (notice the parameter without a leading dash) will still be silently accepted.

I have two questions:

  1. Is there a way to get Powershell to always report an extra argument to my script as an error? In my script, I just want to allow the fixed set of switches (-A, -B, -C), and any other parameter should be an error.

  2. When a parameter error is detected, can I get Powershell to print the usage (i.e., "get-help example.ps1") instead of raising a ParameterBindingException?

Upvotes: 3

Views: 8853

Answers (2)

JPBlanc
JPBlanc

Reputation: 72680

You can just try using CmdletBinding as explain in about_Functions_CmdletBindingAttribute, in functions that have the CmdletBinding attribute, unknown parameters and positional arguments that have no matching positional parameters cause parameter binding to fail.

[CmdletBinding()]
Param(
      [switch] $A,
      [switch] $B,
      [switch] $C)

echo "A:$A, B:$B, C:$C"

Upvotes: 5

CB.
CB.

Reputation: 60976

You can try in this way checking $args

Function myfunction
{
  param(
        [switch] $A,
        [switch] $B,
        [switch] $C
)

foreach ( $key in $PSBoundParameters.keys )
{    
  if ( $args -gt 0) 
        {$script:test = $false ; break}
    else
        {$script:test = $true}
}    

if ($test)     
{ 
 "Parameters are ok" # ... your code script here
}    
else
{
  "Parameters error. Check Command" # or get-help myfuction
}
}

Upvotes: 2

Related Questions