Dominic Brunetti
Dominic Brunetti

Reputation: 1069

Passing unknown number of values to PowerShell script parameter?

I am familiar with how to accept parameters or arguments from the command line and pass them to PowerShell:

powershell.exe -file myscript.ps1 -COMPUTER server1 -DATA abcd
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [string]$computer,

    [Parameter(Mandatory=$True)]
    [string]$data
)

That’s fine, but what if the $computer argument is more than one item and of an unknown number of items? For example:

Powershell.exe -file myscript.ps1 -COMPUTER server1, server2, server3 -DATA abcd

Here we do not know how many $computer items there will be. There will always be one, but there could be 2, 3, 4, etc. How is something like this best achieved?

Upvotes: 4

Views: 5477

Answers (2)

DarkLite1
DarkLite1

Reputation: 14705

You can make the parameter [String]$Computer accept multiple strings (or an array) by using [String[]]$Computer instead.

Example:

Function Get-Foo {
    [CmdletBinding()]
    Param (
       [Parameter(Mandatory=$True)]
       [String[]]$Computer,

       [Parameter(Mandatory=$True)]
       [String]$Data
    )

    "We found $(($Computer | Measure-Object).Count) computers"
}

Get-Foo -Computer a, b, c -Data yes

# We found 3 computers

Get-Foo -Computer a, b, c, d, e, f -Data yes

# We found 6 computers

Upvotes: 7

G42
G42

Reputation: 10019

Specify this in the parameter definition. Change from [String] to an array of strings [String[]]

[CmdletBinding()]
Param(
   [Parameter(Mandatory=$True)]
    [string[]]$computer,

   [Parameter(Mandatory=$True)]
    [string]$data
)

Upvotes: 2

Related Questions