我猜你不能这样做:
$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?
答案 0 :(得分:41)
Keith's answer也适用于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
答案 1 :(得分:30)
scriptblock只是一个匿名函数。你可以在里面使用$args
scriptblock以及声明一个param块,例如
$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
答案 2 :(得分:5)
BTW,如果使用脚本块在单独的线程(多线程)中运行:
$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
答案 3 :(得分:5)
对于任何想在2020年之前阅读并希望在远程会话脚本块中使用局部变量的人,可以从Powershell 3.0开始,通过“ $ Using”作用域修饰符直接在脚本块中使用局部变量。示例:
$MyLocalVariable = "C:\some_random_path\"
acl = Invoke-Command -ComputerName REMOTEPC -ScriptBlock {Get-Acl $Using:MyLocalVariable}
答案 4 :(得分:1)
我知道这篇文章有点陈旧,但我想把它作为一种可能的选择。只是稍微改变了之前的答案。
$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"
答案 5 :(得分:1)
默认情况下,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
答案 6 :(得分:0)
三种示例语法:
$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"
答案 7 :(得分:0)
其他可能性: $a ={ 参数($p1,$p2) “p1 是 $p1” “p2 是 $p2” “其余的参数:$args” } $a.invoke(1,2,3,4,5)