Pass array to PowerShell script executed with -File argument

arrays, parameters, powershell

Solution

Here is another try. Note the `ValueFromRemainingArguments=$true` in the parameters declaration:

param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
    [string[]]$keys)
for ($i = 0; $i -lt $keys.Length; ++$i) {
    Write-Host "$i. $($keys[$i])"
}

Then I called the script via powershell.exe using the -file argument:

powershell.exe -File d:\scripts\array.ps1 "1" "a" "c"

This works to pass all those parameters as an array, the output is:

0. 1
1. a
2. c

In case you need to pass additional parameters you can name them in the usual way, such as:

param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
    [string[]]$keys,
    [string] $dummy)

And you can pass the additional parameters such as this:

powershell.exe -File d:\scripts\array.ps1 "1" "a" "c" -dummy "Z"

The `$dummy` parameter will in this case receive the value `Z` while the values of `"1" "a" "c"` will still be assigned to `$keys` as an array.

So if change the script to display the value of `$dummy` along with the rest I get:

0. 1
1. a
2. c
Dummy param is z

Problem

I have simple script which takes array argument: ``` param( [Parameter(Mandatory=$true)] [string[]]$keys ) for ($i = 0; $i -lt $keys.Length; ++$i) { Write-Host "$i. $($keys[$i])" } ``` I need to execute it via powershell with -File argument (in order to address a TeamCity bug) like so: ``` powershell.exe -File Untitled2.ps1 -keys a ``` How can I pass parameter as array to my script? As long as I pass single key it works well, but it don't want to take more than one element. I tried following among others: ``` powershell.exe -File Untitled2.ps1 -keys a,b powershell.exe -File Untitled2.ps1 -keys:a,b powershell.exe -File Untitled2.ps1 -keys $keys # where $keys is an array ``` Whatever I'd tried either I have "A positional parameter cannot be found" error, or all keys are joined in first array element. Any ideas?

Original source