Reputation: 1690
I want to pass an array to a PowerShell script block. This is the accepted method:
$arr = 1..4;
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList (,$arr)
From my investigations, these alternatives work too:
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList $arr,$arr
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList $arr,$null
And the same issue applies when used list this
$arr = 1..4;
$sb = { Param($li); $li | %{$_}}
$sb.Invoke((,$arr))
I understand the reason for the (,$arr) syntax is that the -ArgumentList parameter is expecting an array of parameters to pass to the script block, and if it gets a single array as its value, it will unpack the array and pass the contents to the script block as multiple parameters. I credit these answers how and why for helping me through this.
The accepted solution looks very ugly to me and I wonder it there is a cleaner way that might be closer to what the designers of PowerShell intended. Please comment.
Perhaps the answer is
& $sb $arr.
Please comment.
Upvotes: 1
Views: 148