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:

  1. is there way powershell report argument script error? in script, want allow fixed set of switches (-a, -b, -c), , other parameter should error.

  2. 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

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -