Powershell script parameters: display help on incorrect usage? -
in powershell v2, trying use param() declaration parse switches passed script. problem can illustrated using script (example.ps1):
param( [switch] $a, [switch] $b, [switch] $c ) echo "$a, $b, $c" my problem script silently ignore incorrect switches. instance, "example.ps1 -asdf" print "false, false, false", instead of reporting incorrect usage user.
i noticed behavior changes if add positional parameter:
param( [switch] $a, [switch] $b, [switch] $c, [parameter(position=0)] $positionalparameter ) echo "a:$a, b:$b, c:$c" now, parameterbindingexception raised if run "example2.ps1 -asdf". but, "example2.ps1 asdf" (notice parameter without leading dash) still silently accepted.
i have 2 questions:
is there way powershell report argument script error? in script, want allow fixed set of switches (-a, -b, -c), , other parameter should error.
when parameter error detected, can powershell print usage (i.e., "get-help example.ps1") instead of raising parameterbindingexception?
you can try using cmdletbinding explain in about_functions_cmdletbindingattribute, in functions have cmdletbinding attribute, unknown parameters , positional arguments have no matching positional parameters cause parameter binding fail.
[cmdletbinding()] param( [switch] $a, [switch] $b, [switch] $c) echo "a:$a, b:$b, c:$c"
Comments
Post a Comment