PowerShell v2.0相当于“get-job | receive-job -AutoRemoveJob -Wait”?

时间:2013-09-27 15:02:44

标签: powershell jobs

与此v3.0代码snippt等效的PowerShell v2.0是什么:

for($i=0; $i -lt $num_jobs; $i++) {
    Write-Host -ForegroundColor Darkgreen "[i] Job" $i "starting..."
    Start-Job -ScriptBlock $insert_data -ArgumentList 'host', 'user', 'pass', 'db', $i, $log_out[$i] | Out-Null;
}

get-job | receive-job -AutoRemoveJob -Wait 

我没有运气试过以下

for($i=0; $i -lt $num_jobs; $i++) {
    Write-Host -ForegroundColor Darkgreen "[i] Job" $i "starting..."
    Start-Job -ScriptBlock $insert_data -ArgumentList 'host', 'user', 'pass', 'db', $i, $log_out[$i] | Out-Null;
}

get-job | receive-job -Wait 
get-job | remove-job 

使用以下命令在PowerShell v2.0上失败:

Remove-Job : The command cannot remove the job with the 3 session identifier be
cause the job is not finished. To remove the job, first stop the job, or use th
e Force parameter.

2 个答案:

答案 0 :(得分:1)

我能为V2提出的最好的是:

Get-Job | % {while ($_.HasMoreData) { Receive-Job $_; Sleep 1 }; Remove-Job $_}

注意:如果您运行多个作业,我建议使用Get-Job -Id参数。此外,1秒睡眠可能有点长,你可以调整说250毫秒。

对于多个工作,您可以这样做:

while ($jobs = Get-Job) { $jobs | %{if ($_.HasMoreData) {Receive-Job $_} else {Remove-Job $_}}; Sleep 1}; 

答案 1 :(得分:0)

以两个不同的方式尝试:

get-job | wait-job | receive-job
get-job | remove-job