Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Invoke-Command -ScriptBlock on a function with arguments

I'm writing a PowerShell script that will execute commands on a remote host using Invoke-Command and its -ScriptBlock parameter. For example,

function Foo {     ...     return "foo" } $rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo} 

This works fine. What I'd like to do now is the same thing, but call a function with local arguments. For example,

function Bar {     param( [String] $a, [Int] $b )     ...     return "foo" } [String] $x = "abc" [Int] $y = 123 $rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo($x,$y)} 

But this does not work:

Invoke-Command : Cannot validate argument on parameter 'ScriptBlock'. The argument is null. Supply a non-null argument and try the command again.

How can I use Invoke-Command with a -ScriptBlock that is a local function with arguments?

I realize that I can wrap the entire function and the parameters in a big code block, but that is not a clean way of doing it, in my opinion.

like image 598
Christopher Neylan Avatar asked Dec 09 '11 16:12

Christopher Neylan


People also ask

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.

What is the use of Invoke command in Cypress?

invoke() automatically retries invoking the specified method until the returned value satisfies the attached assertions.

What does invoke expression do in Powershell?

Description. The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression , a string submitted at the command line is returned (echoed) unchanged. Expressions are evaluated and run in the current scope.


2 Answers

I think you want:

function Foo ( $a,$b) {     $a     $b     return "foo" }  $x = "abc" $y= 123  Invoke-Command -Credential $c -ComputerName $fqdn -ScriptBlock ${function:Foo} -ArgumentList $x,$y 
like image 143
manojlds Avatar answered Oct 03 '22 05:10

manojlds


You can wrap the functions in a block and pass the block;

$a = {   function foo{}   foo($args) }  $a.invoke() // Locally  $rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock $a //remotely 

It's hardly elegant though.

like image 31
reconbot Avatar answered Oct 03 '22 04:10

reconbot