Passing an array to a {scriptblock}

#powershell edit this page

Some Friday PowerShell fun today.

I created a PowerShell script the other day where I was passing a variable to a scriptblock. As long as the variable was a simple string everything was just fine, but when the variable was of the type System.Array only the first item would have been passed to the scriptblock.


Example 1 shows what I mean.

$myArray = "a","b","c"
$myBlock = { param($p1) write $p1 }
Invoke-Command -ScriptBlock $myBlock -ArgumentList $myArray

This example would produce an output of “a” even though I assumed it would output “a”,”b”,”c”.

So I was scratching my head for a while and then tried to do it that way:

$myArray = "a","b","c"
$myBlock = { param($p1) write $p1 }
Invoke-Command -ScriptBlock $myBlock –ArgumentList (,$myArray)

This one works as expected, so it produces an output of “a”,”b”,”c”.


have a nice weekend!