Search code examples
powershelljobs

PowerShell v2.0 equivalent to "get-job | receive-job -AutoRemoveJob -Wait"?


What is the PowerShell v2.0 equivalent to this v3.0 code snippt:

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 

I tried the following without luck

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 

It fails on PowerShell v2.0 with:

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.

Solution

  • The best I can come up with for V2 is:

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

    Note: I recommend using the Get-Job -Id parameter in the event you have more than one job running. Also, a 1 second sleep might be a bit long, you could tweak that to say 250 millisecs.

    For multiple jobs, you could do this:

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