Different from: How to handle command-line arguments in PowerShell
What's the best way to handle an unnamed command-line argument in a powershell script?
For example, I have a powershell script that I would like to run as
.\test.ps1 L3
and have an error if L3 is not supplied. I don't want to have to run it as:
.\test.ps1 -lab L3
My current script:
$args[0]
does not cause an error if the argument is omtted.
This looks promising, haven't tried it yet: https://technet.microsoft.com/en-us/library/hh847743.aspx * Edit: * The promising link is useful -- I used it to form all my examples
-
Why don't you want named arguments (parameters)? They make for much more readable code, and if you set up your parameters properly I think you can leave them unnamed when you pass them in, as long as you do it in the right order.alroc– alroc2015年02月26日 14:42:56 +00:00Commented Feb 26, 2015 at 14:42
-
1Named arguments are great. But this script ALWAYS requires this argument and it will save three-four keystrokes every time I use it.Josiah Yoder– Josiah Yoder2015年02月26日 15:08:08 +00:00Commented Feb 26, 2015 at 15:08
-
3If it's the only argument, you can make it named and pass it in un-named and PowerShell will handle it just fine. Don't write for your convenience - write to make your script understandable for the next person who has to use it and isn't you.alroc– alroc2015年02月26日 15:11:57 +00:00Commented Feb 26, 2015 at 15:11
-
1My point remains. Even at the command line, write for the understanding of the next person, not for your convenience. Named parameters are almost always a good thing, regardless - when someone has to modify this script to add another parameter, they'll want them named. It costs you nothing to make it named now, just do it.alroc– alroc2015年02月26日 15:29:26 +00:00Commented Feb 26, 2015 at 15:29
-
1This seems like a potentially contentious point. Perhaps it's just my bash background, but I find unnamed parameters for one or two essential arguments to be perfectly readable in many cases. Perhaps this is an exception.Josiah Yoder– Josiah Yoder2015年02月26日 15:41:21 +00:00Commented Feb 26, 2015 at 15:41
1 Answer 1
This did the trick:
Param
(
[parameter(Position=0, Mandatory=$true)]
[String]
$LabNumber
)
$LabNumber
This second option is interesting, but I prefer the Mandatory=$true above, because it will actually prompt you to enter it if you forget it.
Param
(
[parameter(Position=0)]
[String]
$LabNumber=$(throw "LabNumber is required. Usage Example: .\test.ps1 L3")
)
$LabNumber
And, as @alroc prefers for all parameters, the second parameter must be named:
Param
(
[parameter(Position=0, Mandatory=$true)]
[String]
$LabNumber,
[alias("Submissions")]
[String]
$LoginsFilename = "..\logins.txt"
)
"LabNumber:"+$LabNumber
"LoginsFilename:"+$LoginsFilename
Comments
Explore related questions
See similar questions with these tags.