'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?
Solution 1:[1]
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 -AutoRemoveJob
:
$jobs = foreach($service in $services) {
Start-Job -ScriptBlock $stopService -ArgumentList $service
}
Receive-Job $jobs -Wait -AutoRemoveJob
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
}
This answer shows a similar, more developed alternative, using a function to wait for Jobs with progress and a optional TimeOut parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |