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:
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.
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?