Take the 2-minute tour ×

I am sooo stuck on something this morning. The "best" way to handle command line arguments. It seems like there are several answers on what the "best" way is and as a result I am stuck on how to handle something as simple as: script.ps1 /n name /d domain AND script.ps1 /d domain /n name.

Is there a plugin that can handle this better? I know I am reinventing the wheel here.

Obviously what I have already isn't pretty and surely isn't the "best", but it works.. and it is UGLY.

for ( $i = 0; $i -lt $args.count; $i++ ) {
        if ($args[ $i ] -eq "/n"){ $strName=$args[ $i+1 ]}
        if ($args[ $i ] -eq "-n"){ $strName=$args[ $i+1 ]}
        if ($args[ $i ] -eq "/d"){ $strDomain=$args[ $i+1 ]}
        if ($args[ $i ] -eq "-d"){ $strDomain=$args[ $i+1 ]}
Write-Host $strName
Write-Host $strDomain
share|improve this question
add comment

1 Answer

up vote 110 down vote accepted

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file (see tutorial: http://devcentral.f5.com/weblogs/Joe/archive/2009/01/13/powershell-abcs---p-is-for-parameters.aspx)

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [string]$username = $(throw "-username is required."),
    [string]$password = $( Read-Host "Input password, please" )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might as well want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [switch]$force = $false

Inside the script then you would work with it like this:

if ($force -eq $true) {
  //deletes a file or does something "bad"
share|improve this answer
AWESOME! And funny because originally I was trying to use param but strayed away from it because I couldn't figure out the syntax. LOL Thank you! –  Aaron Wurthmann Jan 28 '10 at 20:24
Indeed one of PowerShell's big advantages is that it provides a standard parameter parsing infrastucture that is easy to use. –  Keith Hill Jan 28 '10 at 20:43
You have "-site" in the command line example and it doesn't match "[string]$server" in the script Is that a typo? –  JasDev Oct 27 '12 at 16:53
JasDev - yes, that was a typo. Fixed. –  naivists Oct 28 '12 at 18:52
2010 eh? Is it too late to point out you only need if($force) –  haymansfield Feb 5 at 16:46
add comment

Your Answer


