Search code examples
powershellpowershell-2.0powershell-remoting

why does a scriptblock passed as an argument in invoke-commands argumentlist fail?


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

Solution

  • 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
    }