Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 Sservices) {
  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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading