PowerShell Bounded Worker Pool with ForEach-Object Parallel
PowerShell
function Invoke-WorkerPool {
param(
[Parameter(Mandatory)][object[]]$Items,
[Parameter(Mandatory)][scriptblock]$Worker,
[ValidateRange(1, 64)][int]$ThrottleLimit = 4
)
$results = $Items | ForEach-Object -Parallel {
$work = $using:Worker
$item = $_
try {
[pscustomobject]@{ Item = $item; Ok = $true; Value = (& $work $item); Error = $null }
} catch {
[pscustomobject]@{ Item = $item; Ok = $false; Value = $null; Error = $_.Exception.Message }
}
} -ThrottleLimit $ThrottleLimit
[pscustomobject]@{
Results = @($results | Where-Object { $_.Ok })
Errors = @($results | Where-Object { -not $_.Ok })
}
}