Passing multiple values to a single PowerShell script parameter

jcarpio picture jcarpio · Feb 27, 2013 · Viewed 238.4k times · Source

I have a script to which I pass server name(s) in $args.

This way I can do stuff to this (these) server(s) using foreach:

.\script.ps1 host1 host2 host3

foreach ($i in $args)
{
    Do-Stuff $i
}

I'd like to add a named optional parameter called vlan. I've tried:

Param(
    [string]$vlan
)

foreach ($i in $args)
{
    Write-Host $i
}
Write-Host $vlan

It works if you pass a -vlan parameter but if you don't then the script auto assigns the last server name to $vlan.

So, how can you pass single or multiple parameters plus an optional named parameter to a PowerShell script?

Ideally, here are valid examples:

.\script.ps1 host1
.\script.ps1 host1 host2 host3
.\script.ps1 host1 host2 -vlan office

Answer

Bill_Stewart picture Bill_Stewart · Feb 27, 2013

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.