4

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?

2 Answers 2

7

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

Comments

2

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.