Passing multiple values to a single PowerShell script parameter Passing multiple values to a single PowerShell script parameter powershell powershell

Passing multiple values to a single PowerShell script parameter


The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.


Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(    [Parameter(Position = 0)]    [string[]]$Hosts,    [string]$VLAN    )foreach ($i in $Hosts)  {     Do-Stuff $i}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array


One way to do it would be like this:

 param(       [Parameter(Position=0)][String]$Vlan,       [Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts    ) ...

This would allow multiple hosts to be entered with spaces.