Run N parallel jobs in powershell

后端 未结 6 1533
忘了有多久
忘了有多久 2020-12-07 23:18

I have the following powershell script

$list = invoke-sqlcmd \'exec getOneMillionRows\' -Server...
$list | % {
    GetData $_ > $_.txt
    ZipTheFile $_.t         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 23:58

    Same idea as user "Start-Automating" posted, but corrected the bug about forgetting to start the jobs that are held back when hitting the else clause in his example:

    $servers = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n')
    
    foreach ($server in $servers) {
        $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
        if ($running.Count -ge 4) {
            $running | Wait-Job -Any | Out-Null
        }
    
        Write-Host "Starting job for $server"
        Start-Job {
            # do something with $using:server. Just sleeping for this example.
            Start-Sleep 5
            return "result from $using:server"
        } | Out-Null
    }
    
    # Wait for all jobs to complete and results ready to be received
    Wait-Job * | Out-Null
    
    # Process the results
    foreach($job in Get-Job)
    {
        $result = Receive-Job $job
        Write-Host $result
    }
    
    Remove-Job -State Completed
    

提交回复
热议问题