tags:

views:

210

answers:

1

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
+5  A: 

You are reinventing the weel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -site 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 and read them from console if not available:

 param (
    [string]$server = "http://defaultserver"
   ,[string]$Password = $( Read-Host "Input password, please" )
 )

now you can simply

write-output $server

since you have $server as normal variable.

naivists
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
Indeed one of PowerShell's big advantages is that it provides a standard parameter parsing infrastucture that is easy to use.
Keith Hill