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

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

2 Comments

Doesn't really answer the question. The real problem is in passing it in ArgumentList
I say that because even with scriptblock prop it doesn't work from ArgumentList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.