Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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. E.g.,

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.

share|improve this question

3 Answers

up vote 10 down vote accepted

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
share|improve this answer
thanks man, works perfectly! I was messing with combos of param() + -Arguments with no luck. – Christopher Neylan Dec 9 '11 at 17:21
took me several hours to find this solution ;-) Much better than exporting/importing sessions Thank You! – icnivad Jan 13 '12 at 16:50

This also works:

function foo
{
    param([string]$hosts, [string]$commands)
    $scriptblock = $executioncontext.invokecommand.NewScriptBlock($commands)
    $hosts.split(",") |% { Invoke-Command -Credential $cred -ComputerName $_.trim() -Scriptblock $scriptblock }
}
share|improve this answer

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.

share|improve this answer
I'd like to avoid this. – Christopher Neylan Dec 9 '11 at 17:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.