6
function test-scriptblock {
1..10 }
function caller ([scriptblock]$runthis) {
& $runthis
}

the following works fine.

caller -runthis ${function:test-scriptblock}

this doesn't work

invoke-command -ComputerName localhost -ScriptBlock ${function:caller} -ArgumentList ${function:test-scriptblock}

Cannot process argument transformation on parameter 'runthis'. Cannot convert the "
1..10 " value of type "System.String" to type "System.Management.Automation.ScriptBlock".
+ CategoryInfo          : InvalidData: (:) [], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
klumsy
  • 4,081
  • 5
  • 32
  • 42

3 Answers3

6

I verified that this a "known issue". While in most cases in remoting scriptblocks regurgitate just fine as scriptblocks but with ArgumentList they don't, so instead I do

function Caller($runthis)
{
   $runthis = [Scriptblock]::Create($runthis)
   &$runthis
}
participant
  • 2,923
  • 2
  • 23
  • 40
klumsy
  • 4,081
  • 5
  • 32
  • 42
2

Since -ArgumentList takes in Object[], I think it is received by caller as a string. One workaround is this:

function caller ($runthis) {
$runthis = $executioncontext.InvokeCommand.NewScriptBlock($runthis)
& $runthis
}

Note that something like this works:

function caller ($runthis) {
$runthis  | kill
}

$p= Get-Process -name notepad
invoke-command -computer localhost -ScriptBlock ${function:caller} -ArgumentList $p

I think scriptblocks are treated differently since it might be considered a security issue to just run them.

manojlds
  • 290,304
  • 63
  • 469
  • 417
0

Adapted to your initial code, I do it so :

caller -runthis (get-item Function:\test-scriptblock).scriptblock

A function is not a scriptblock, a scriptblock is a property of a function.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175