将参数传递给powershell中的scriptblock



我想你不能这样做:

  $servicePath = $args[0]
  if(Test-Path -path $servicePath) <-- does not throw in here
  $block = {
        write-host $servicePath -foreground "magenta"
        if((Test-Path -path $servicePath)) { <-- throws here.
              dowork 
        }
  }

那么我如何将变量传递给scriptblock $block呢?

Keith的答案也适用于Invoke-Command,但限制是不能使用命名参数。参数应该使用-ArgumentList参数设置,并且应该用逗号分隔。

$sb = {
    param($p1,$p2)
    $OFS=','
    "p1 is $p1, p2 is $p2, rest of args: $args"
}
Invoke-Command $sb -ArgumentList 1,2,3,4

scriptblock只是一个匿名函数。你可以在里面使用$argsScriptblock以及声明参数块,例如

$sb = {
  param($p1, $p2)
  $OFS = ','
  "p1 is $p1, p2 is $p2, rest of args: $args"
}
& $sb 1 2 3 4
& $sb -p2 2 -p1 1 3 4

对于任何想要在远程会话脚本块中使用本地变量的人来说,从Powershell 3.0开始,您可以直接在scriptblock中使用"$Using"范围修饰符使用本地变量。例子:

$MyLocalVariable = "C:some_random_path"
acl = Invoke-Command -ComputerName REMOTEPC -ScriptBlock {Get-Acl $Using:MyLocalVariable}

出现在https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7

的例9中

顺便说一句,如果使用脚本块在单独的线程(多线程)中运行:

$ScriptBlock = {
    param($AAA,$BBB) 
    return "AAA is $($AAA) and BBB is $($BBB)"
}
$AAA = "AAA"
$BBB = "BBB1234"    
$null = Start-Job $ScriptBlock -ArgumentList $AAA,$BBB

则产生:

$null = Start-Job $ScriptBlock -ArgumentList $AAA,$BBB    
Get-Job | Receive-Job
AAA is AAA and BBB is BBB1234

默认情况下,PowerShell不会捕获ScriptBlock的变量。但是,您可以通过对其调用GetNewClosure()来显式捕获:

$servicePath = $args[0]
if(Test-Path -path $servicePath) <-- does not throw in here
$block = {
    write-host $servicePath -foreground "magenta"
    if((Test-Path -path $servicePath)) { <-- no longer throws here.
          dowork 
    }
}.GetNewClosure() <-- this makes it work

三个语法示例:

$a ={ 
  param($p1, $p2)
  "p1 is $p1"
  "p2 is $p2"
  "rest of args: $args"
}
//Syntax 1:
Invoke-Command $a -ArgumentList 1,2,3,4 //PS> "p1 is 1, p2 is 2, rest of args: 3 4"
//Syntax 2:
&$a -p2 2 -p1 1 3      //PS> "p1 is 1, p2 is 2, rest of args: 3"
//Syntax 3:
&$a 2 1 3              //PS> "p1 is 2, p2 is 1, rest of args: 3"

我知道这篇文章有点过时了,但我想把这篇文章作为一个可能的替代方案。只是和之前的答案略有不同。

$foo = {
    param($arg)
    Write-Host "Hello $arg from Foo ScriptBlock" -ForegroundColor Yellow
}
$foo2 = {
    param($arg)
    Write-Host "Hello $arg from Foo2 ScriptBlock" -ForegroundColor Red
}

function Run-Foo([ScriptBlock] $cb, $fooArg){
    #fake getting the args to pass into callback... or it could be passed in...
    if(-not $fooArg) {
        $fooArg = "World" 
    }
    #invoke the callback function
    $cb.Invoke($fooArg);
    #rest of function code....
}
Clear-Host
Run-Foo -cb $foo 
Run-Foo -cb $foo 
Run-Foo -cb $foo2
Run-Foo -cb $foo2 -fooArg "Tim"

其他可能性:

$a ={ 
    param($p1, $p2)
    "p1 is $p1"
    "p2 is $p2"
    "rest of args: $args"
};
$a.invoke(1,2,3,4,5)

相关内容

  • 没有找到相关文章

最新更新