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.

Nigel Davies
  • 1,640
  • 1
  • 13
  • 26
  • 2
    Why are you using `Invoke-Command` here? – Mathias R. Jessen Dec 27 '22 at 10:38
  • `$using:` is simpler but works for remote sessions – Santiago Squarzon Dec 27 '22 at 12:24
  • Nope. But usually invoke-command is for remote computers. – js2010 Dec 27 '22 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) – Nigel Davies Dec 28 '22 at 05:16
  • Thanks for closing: not! I found those older examples too, but to me, the say what to do, but not clearly why. – Nigel Davies Dec 28 '22 at 05:17
  • @MathiasR.Jessen: i am using Invoke-Command to run a lambda or anonymous function (in a script block) Is there a better way? – Nigel Davies Dec 28 '22 at 05:19
  • [This question](https://stackoverflow.com/questions/57829773/how-to-pass-array-into-anonymous-function) seems to be the most complete explanation of this issue and compares various solutions. – Nigel Davies Dec 28 '22 at 06:36
  • @NigelDavies Yes, use [the call operator `&`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.3#call-operator-) :) – Mathias R. Jessen Dec 28 '22 at 11:23

0 Answers0