代码之家  ›  专栏  ›  技术社区  ›  Chris F

在Powershell中,如何等待并行作业完成后再继续?

  •  3
  • Chris F  · 技术社区  · 4 年前

    基于 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() 命令

    1 回复  |  直到 4 年前
        1
  •  3
  •   Santiago Squarzon    4 年前

    您可以捕获 PSRemotingJob 归还人 Start-Job 在变量中,然后使用 Wait-Job 或者使用 Receive-Job -Wait -AutoRemove :

    $jobs = foreach($service in Sservices) {
        Start-Job -ScriptBlock $stopService -ArgumentList $service
    }
    
    Receive-Job $jobs -Wait -AutoRemove
    

    还有其他的选择,比如在 this answer ,使用循环。例如:

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

    然而,手头的案子似乎并不需要。

    推荐文章