我正在尝试获取在脚本块内修改的变量的值:
function Test-Function {
$var = "apple"
Start-Job -ScriptBlock {
$var = "banana"
}
Write-Host "Variable is $var"
}
Test-Function
Variable is: apple
我正在尝试获取输出“香蕉”。这可能吗?
答案 0 :(得分:3)
由于在代码中使用PS Jobs,因此需要使用wait-job
使用wait等待作业完成,最后必须使用receive-job
接收该作业。用以下代码替换您的代码:
function Test-Function {
$var = "apple"
Start-Job -ScriptBlock {
$var = "banana"
Write-Host "Variable is $var"
} | Wait-Job -Any |Receive-Job
#Write-Host "Variable is $var"
}
Test-Function
希望有帮助。