史蒂夫湯森的回答在理論上是正確的,但在實踐中卻沒有,正如@likwid指出的那樣。我修改后的代碼考慮了工作環(huán)境障礙 -默認情況下沒有任何障礙超越這個障礙!因此,自動$_
變量可以在循環(huán)中使用,但不能直接在腳本塊中使用,因為它位于作業(yè)創(chuàng)建的單獨上下文中。
要將變量從父上下文傳遞到子上下文,請使用-ArgumentList
參數(shù)on Start-Job
發(fā)送它并param
在腳本塊內(nèi)部使用它來接收它。
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文檔的參考作為支持證據(jù),但是,唉,我的搜索沒有結(jié)果。如果您碰巧知道上下文分離的記錄,請在此發(fā)表評論以告訴我!)