How to handle command-line arguments in PowerShell

What is 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

1
1

Leave a Comment