Home > Blockchain >  In Powershell, how to wait for parallel jobs to finish before proceeding?
In Powershell, how to wait for parallel jobs to finish before proceeding?

Time:03-06

Based on How to execute a PowerShell function several times in parallel?, I'm able to do this, where I stop all running jobs, in parallel.

# Run this in parallel
$stopService {
  param($service)
  Stop-Service -Name $service.name -Force
}

$services = Get-Services | Where-Oject {$_.name -like "*XYX_*"}
Foreach($service in Sservices) {
  Start-Job -ScriptBlock $stopService -ArgumentList $service
}

$doSomethingElse

But how can I modify the code so all my parallel jobs finish first before I $doSomethingElse?. Kinda like a join() command?

CodePudding user response:

You can capture all the instances of PSRemotingJob returned by Start-Job in a variable and then wait for them either using Wait-Job or using Receive-Job -Wait -AutoRemove:

$jobs = foreach($service in $services) {
    Start-Job -ScriptBlock $stopService -ArgumentList $service
}

Receive-Job $jobs -Wait -AutoRemove

There are other alternatives, such as the one displayed in this answer, using a loop. For example:

while($jobs.State -contains 'Running') {
   # do something here, track progress, etc
   Start-Sleep 1
}

However for the case at hand doesn't seem to be needed.

  • Related