Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 422
Dominic Brunetti Avatar asked Sep 01 '25 21:09

Dominic Brunetti


2 Answers

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
like image 133
DarkLite1 Avatar answered Sep 03 '25 11:09

DarkLite1


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
)
like image 32
G42 Avatar answered Sep 03 '25 11:09

G42