Why does the script block passed as an argument in the argument list of invoke commands fail?

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

works great.

 caller -runthis ${function:test-scriptblock} 

this does not 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 
+6
source share
3 answers

I confirmed that this is a "known issue." Although in most cases, when deleting script blocks, they are smoothed just like script blocks, but they do not do this with ArgumentList , so instead I do

 function Caller($runthis) { $runthis = [Scriptblock]::Create($runthis) &$runthis } 
+6
source

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

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

Please 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 script blocks are handled differently, as this may be considered a security issue, just to run them.

+2
source

Adapted to the source code, I do it like this:

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

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

0
source

Source: https://habr.com/ru/post/895793/


All Articles