1

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?

mccormickt12
  • 575
  • 1
  • 7
  • 14
  • 1
    Considering you say you don't want a string, can you clarify what you are asking? Meaning are you trying to pass these and assign them to a single hash table object, assign them as [params](http://stackoverflow.com/questions/5592531/how-to-pass-an-argument-to-a-powershell-script), pass them directly to a starting function (as arguments), or something else? – LinkBerest Jul 21 '16 at 22:52
  • Are you looking for [`$args`](https://technet.microsoft.com/en-us/library/hh847768.aspx)? What is the purpose of this? Why can't you simply use optional parameters? – Ansgar Wiechers Jul 22 '16 at 13:34
  • I want to have one script be called (kind of acting as a parent) and then based on the first parameter blindly pass the rest of the arguments to another script. So I want the "-params" too – mccormickt12 Jul 22 '16 at 17:31

2 Answers2

5

You could use the ValueFromRemainingArguments option in the Parameter attribute of your one variable

script.ps1

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
Community
  • 1
  • 1
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

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: $_" }
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328