I'm trying to create a powershell (2.0) script that will accept arguments that follow this basic pattern:
.{script name} [options] PATH
Where options are any number of optional parameters - think along the lines of '-v' for verbose. The PATH argument will simply be whatever argument is passed in last, and is mandatory. One could call the script with no options and only one argument, and that argument would be assumed to be the Path. I'm having trouble setting up a parameters list that contains only optional parameters but is also non-positional.
This quick script demonstrates the problem I am having:
#param test script
Param(
$firstArg,
$secondArg,
[switch]$thirdArg,
[Parameter(ValueFromRemainingArguments = $true)]
$remainingArgs)
write-host "first arg is $firstArg"
write-host "second arg is $secondArg"
write-host "third arg is $thirdArg"
write-host "remaining: $remainingArgs"
When called like so:
.param-test.ps1 firstValue secondValue
The script outputs:
first arg is firstValue
second arg is secondValue
third arg is False
remaining:
The behavior I am trying to create would have both arguments fall through the optional params and end up in the remainingArgs variable.
This question/answer helpfully provided a way to achieve the desired behavior, but it only seems to work if there is at least one mandatory parameter, and only if it comes before all of the other arguments.
I can demonstrate this behavior by making firstArg mandatory and specifying a position of 0:
#param test script
Param(
[Parameter(Mandatory=$true, Position = 0)]
$firstArg,
$secondArg,
[switch]$thirdArg,
[Parameter(ValueFromRemainingArguments = $true)]
$remainingArgs)
write-host "first arg is $firstArg"
write-host "second arg is $secondArg"
write-host "third arg is $thirdArg"
write-host "remaining: $remainingArgs"
Run with the same input as before:
.param-test.ps1 firstValue secondValue
The output is as follows:
first arg is firstValue
second arg is
third arg is False
remaining: secondValue
The first, mandatory argument is assigned, and everything left falls all the way through.
The question is this: How can I set up a params list such that all of the params are optional, and none of them is positional?
See Question&Answers more detail:
os