How to use the foreach loop parallelly in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

There are two ways to use the foreach loop parallelly in PowerShell.

  • Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)

  • Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)

Suppose we have Servers.txt and which contains 10 Servers. When we use the Parallel for loop, it isn’t guaranteed which server loop will pick first as shown below with two examples.

  • Using Foreach-Object-Parallel command. (not Foreach -Parallel)

This Foreach-Object -Parallel command feature is newly added to the PowerShell version 7.0 or above.

Example

$servers = Get-Content C:\Temp\Servers.txt

$servers | foreach-Object -parallel{
   Write-output "Working on $_"
}

Output

PS C:\> C:\Temp\Test1.ps1
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
Working on USServer001
Working on IndiaServer005
Working on USServer002
Working on IndiaServer006
Working on NZServer001
Working on NZServer002

If you have more servers, you can also set the -Throttlelimit parameter but need to make sure that the system should not get exhausted due to the throttle limit because it will create more runspaces.

  • Using PowerShell Workflow.

If you are working with PowerShell 5.1, we can use Workflow feature Foreach -Parallel to run the loop parallelly. For example,

Example

Workflow TestParallel{
   Foreach -parallel($server in (Get-Content C:\Temp\Servers.txt)){
      Write-Output "Working on $Server"
   }
}

TestParallel

Output

PS C:\WINDOWS\system32> C:\Temp\Test1.ps1
Working on NZServer002
Working on NZServer001
Working on USServer002
Working on USServer001
Working on IndiaServer006
Working on IndiaServer005
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
raja
Published on 19-Feb-2021 13:01:21
Advertisements