我猜你不能这样做:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
那么如何将我的变量传递给scriptblock $ block?
PowerShell ScriptBlock不是词法闭包,因为它不会关闭其声明环境中引用的变量.相反,似乎利用动态范围和自由变量,这些变量在运行时绑定在lambda表达式中.
function Get-Block {
$b = "PowerShell"
$value = {"Hello $b"}
return $value
}
$block = Get-Block
& $block
# Hello
# PowerShell is not written as it is not defined in the scope
# in which the block was executed.
function foo {
$value = 5
function bar {
return $value
}
return bar
}
foo
# 5
# 5 is written $value existed during the evaluation of the bar function
# it is my understanding …
Run Code Online (Sandbox Code Playgroud)