Last active
July 5, 2019 19:46
-
-
Save countzero/87ef1a5e187c7479972576f6a282e8d3 to your computer and use it in GitHub Desktop.
Execute PowerShell jobs in parallel with a max concurrency using the Wait-Job strategy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$maxConcurrentJobs = 5 | |
for ($index=1; $index -le 23; $index++) { | |
$runningJobs = $(Get-Job -State Running) | |
$concurrencyLimitIsReached = $($runningJobs.Count -ge $maxConcurrentJobs) | |
if ($concurrencyLimitIsReached) { | |
Write-Host "Reached concurrency limit of ${maxConcurrentJobs}, waiting for a job to complete..." | |
$runningJobs | Wait-Job -Any | Out-Null | |
} | |
$scriptBlock = { | |
Param ( | |
[string] [Parameter(Mandatory=$true)] $id | |
) | |
$durationInMilliseconds = $(Get-Random -Minimum 500 -Maximum 1000) | |
Start-Sleep -Milliseconds $durationInMilliseconds | |
Write-Host "Job #${id} completed in ${durationInMilliseconds} ms." | |
} | |
Write-Host "Starting Job #${index}..." | |
Start-Job $scriptBlock -Name "Job #${index}" -ArgumentList $index | Out-Null | |
} | |
Get-Job | Receive-job -AutoRemoveJob -Wait |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will output the job results after all jobs have been completed in the order they were started: