I want to have variable number of args go into one variable
script.ps1 first -second a -third b
what I want is to have "first -second a -third b" all be in one variable.
Is this possible without passing all the arguments as one string?
I want to have variable number of args go into one variable
script.ps1 first -second a -third b
what I want is to have "first -second a -third b" all be in one variable.
Is this possible without passing all the arguments as one string?
You could use the ValueFromRemainingArguments
option in the Parameter
attribute of your one variable
param(
[Parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
[psobject[]]$InputObject
)
foreach($value in $InputObject)
{
Write-Host $value
}
Now you can supply as many arguments as you want to:
PS C:\> .\script.ps1 many arguments can go here
many
arguments
can
go
here
If you want to treat the first argument in the list as a subcommand and pass the rest of the arguments on to other functions/cmdlets I'd simply split'n'splat the automatic variable $args
, e.g. like this:
$subcommand, $params = $args
switch ($subcommand) {
'foo' { Do-Some @params }
'bar' { Do-Other @params }
default { Write-Error "Unknown subcommand: $_" }
}