Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 555
klumsy Avatar asked Aug 24 '11 19:08

klumsy


People also ask

What does Scriptblock do in PowerShell?

In the PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. A script block returns the output of all the commands in the script block, either as a single object or as an array.

What is ArgumentList in PowerShell?

-ArgumentListSpecifies parameters or parameter values to use when this cmdlet starts the process. Arguments can be accepted as a single string with the arguments separated by spaces, or as an array of strings separated by commas.

How does invoke-Command work?

The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a single Invoke-Command command, you can run commands on multiple computers. To run a single command on a remote computer, use the ComputerName parameter.

How do I run a PowerShell script from the Command line?

To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. The script must be on or accessible to your local computer. The results are returned to your local computer.


1 Answers

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
}
like image 162
klumsy Avatar answered Sep 17 '22 18:09

klumsy