1 min read

Run PowerShell loops in parallel


Parallel loops in PowerShell 7+

Run operations concurrently:

parallel.ps1
$vms = Get-AzVM -ResourceGroupName "myRG"
$vms | ForEach-Object -Parallel {
    $vm = $_
    Write-Output "Processing $($vm.Name)"
    Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
} -ThrottleLimit 5

The -ThrottleLimit controls max concurrent threads.

Note: Variables from the outer scope need $using: prefix:

parallel_using.ps1
$tag = "environment"
$vms | ForEach-Object -Parallel {
    $t = $using:tag
    Get-AzTag -ResourceId $_.Id | Where-Object { $_.Properties.TagsProperty.ContainsKey($t) }
} -ThrottleLimit 10