Using Workflows to Parallelize Code

by Feb 22, 2016

If you want to execute more than one thing at once, there are many ways to implement this in PowerShell. One may be the use of workflows. They were introduced in PowerShell 3.0:

#requires -Version 3
workflow Test-ParallelForeach
{
  param
  (
    [String[]]
    $ComputerName
  )

  foreach -parallel -throttlelimit 8 ($Machine in $ComputerName)
  {
    "Begin $Machine"
    Start-Sleep -Seconds (Get-Random -min 3 -max 5)
    "End $Machine"
  }
}

$list = 1..20

Test-ParallelForeach -ComputerName $list | Out-GridView

Test-ParallelForeach runs a list of computers (in this sample, it is a list of numbers). They all run at the same time. To control resource usage, the parallel loop does use a throttle limit of 8, so the 20 computers in this sample run in groups of 8.

Note that workflows do require more knowledge about their architecture and limitations. This example focuses on the parallel loop technique supported by workflows.

Twitter This Tip! ReTweet this Tip!