在 Powershell 中,如何在继续之前等待并行作业完成?
In Powershell, how to wait for parallel jobs to finish before proceeding?
基于 How to execute a PowerShell function several times 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
但是我如何修改代码,以便我的所有并行作业在 $doSomethingElse
之前先完成?。有点像 join()
命令?
您可以捕获 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
还有其他替代方案,例如 中显示的那个,使用循环。例如:
while($jobs.State -contains 'Running') {
# do something here, track progress, etc
Start-Sleep 1
}
显示了一个类似的、更发达的替代方案,使用一个函数来等待有进度的作业和一个可选的 TimeOut参数。
基于 How to execute a PowerShell function several times 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
但是我如何修改代码,以便我的所有并行作业在 $doSomethingElse
之前先完成?。有点像 join()
命令?
您可以捕获 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
还有其他替代方案,例如
while($jobs.State -contains 'Running') {
# do something here, track progress, etc
Start-Sleep 1
}