using "-?" as parameter

Topics: Developer Forum, User Forum
Mar 16, 2009 at 6:46 PM
I am new to powershell and try to find a way to implement "-?" as a help switch in my script.  However, using hyphen in the parameter does get recognized by the "if ($help eq "-?")" statement.  Please refer to the following sample code for detail:

if($help eq "-?")
 write-host "test help switch"

Running ".\helptest.ps1 -?" cmd on the PS prompt does not print anything.
Any feedback will be greatly appreicated. 


Mar 16, 2009 at 7:37 PM
PowerShell knows that - means a new argument. If you write -? then the name of the argument would have to be "?" which isn't allowed, because $? is a special variable.  Despite that, you CAN do what you're trying to do, BUT please bear in mind that in PowerShell 2.0 the -? switch is coopted by the shell for the "autohelp" feature which will require you to rewrite this code, because you can't do this in a forwards compatible way:

$ARGS is the array of parameters which didn't match things in your PARAM(...) block, so you just do this:

if($args -contains "-?") [ write-host "here's your help" ]

You don't have to worry about this matching -?foo  because $args is an array, and -contains is testing each item in the array for equality.
Mar 16, 2009 at 8:12 PM
Works great!!  Thanks much! :-)