史蒂夫汤森的回答在理论上是正确的,但在实践中却没有,正如@likwid指出的那样。我修改后的代码考虑了工作环境障碍 -默认情况下没有任何障碍超越这个障碍!因此,自动$_变量可以在循环中使用,但不能直接在脚本块中使用,因为它位于作业创建的单独上下文中。
要将变量从父上下文传递到子上下文,请使用-ArgumentList参数on Start-Job发送它并param在脚本块内部使用它来接收它。cls# Send in two root directory names, one that exists and one that does not.# Should then get a "True" and a "False" result out the end."temp", "foo" | %{
$ScriptBlock = {
# accept the loop variable across the job-context barrier
param($name)
# Show the loop variable has made it through!
Write-Host "[processing '$name' inside the job]"
# Execute a command
Test-Path "\$name"
# Just wait for a bit...
Start-Sleep 5
}
# Show the loop variable here is correct
Write-Host "processing $_..."
# pass the loop variable across the job-context barrier
Start-Job $ScriptBlock -ArgumentList $_}# Wait for all to completeWhile (Get-Job -State "Running") { Start-Sleep 2 }# Display output from all jobsGet-Job | Receive-Job# CleanupRemove-Job *
(我通常喜欢提供PowerShell文档的参考作为支持证据,但是,唉,我的搜索没有结果。如果您碰巧知道上下文分离的记录,请在此发表评论以告诉我!)