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?

3
  • 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, pass them directly to a starting function (as arguments), or something else? Commented Jul 21, 2016 at 22:52
  • Are you looking for $args? What is the purpose of this? Why can't you simply use optional parameters? Commented Jul 22, 2016 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 Commented Jul 22, 2016 at 17:31

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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: $_" }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.