1

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.

8
  • 2
    Why are you using Invoke-Command here? Commented Dec 27, 2022 at 10:38
  • $using: is simpler but works for remote sessions Commented Dec 27, 2022 at 12:24
  • Nope. But usually invoke-command is for remote computers. Commented Dec 27, 2022 at 16:28
  • @js2010: this is a simplified example to understand the problem. I am exploring lambda functions and functional programming with powershell, inspired by the accumulate exercise from exercism for powershell. (Google it: it is not fully released yet) Commented Dec 28, 2022 at 5:16
  • Thanks for closing: not! I found those older examples too, but to me, the say what to do, but not clearly why. Commented Dec 28, 2022 at 5:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.