Using Invoke-Command -ScriptBlock on a function with arguments

后端 未结 3 972
遥遥无期
遥遥无期 2020-11-29 22:08

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

         


        
相关标签:
3条回答
  • 2020-11-29 22:13

    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 }
    }
    
    0 讨论(0)
  • 2020-11-29 22:16

    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
    
    0 讨论(0)
  • 2020-11-29 22:25

    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.

    0 讨论(0)
提交回复
热议问题