Quick PowerShell snippet to show ForEach -parallel differences when leveraging PowerShell Workflow

A colleague shared a blog post regarding the use of the foreach loops with the parallel parameter in PowerShell Workflow (  https://sqlblog.com/blogs/jamie_thomson/archive/2014/12/09/parallel-foreach-loops-one-reason-to-use-powershell-workflow-instead-of-ssis.aspx ). I wanted to do a quick test to see some of the overhead so I wrote a quick snippet with Start-Sleep within a foreach loop. The PowerShell below is for example purposes only. There is most likely an intercept or titration point in which the use of -parallel would not be needed. In other words, if only processing 5 or so objects that are completed very quickly. I see were the use of the -parallel parameter could be extremely useful when attempting to process a large collection of objects (e.g. SharePoint Site Collections) and the methods you are using do not impact each other.

# Script

workflow WFCheckTiming

{

    Param ([int]$NumberOfIterations, [Int] $Delay)

    "$NumberofIterations iterations with a $Delay milliseconds delay"

    $array = 1..$NumberOfIterations

    $StartTime = Get-Date

    ForEach ($i in $array)

    {

        Start-Sleep -Milliseconds $Delay

    }

    "serial : "

    ((Get-Date) - $StartTime).TotalMilliSeconds

   

    $StartTime = Get-Date

    ForEach -parallel  ($i in $array)

    {

        Start-Sleep -Milliseconds $Delay

    }

    "parallel :" 

    ((Get-Date) - $StartTime).TotalMilliSeconds

}

Clear-Host

WFCheckTiming -NumberOfIterations 50 -Delay 150

# Output in milliseconds

50 iterations with a 150 milliseconds delay
serial :
7985.0853
parallel :
520.4536

[caption id="attachment_1495" align="alignnone" width="300"]Screenshot of PowerShell Script for quick evaluation of ForEach -parallel PowerShell Script for quick evaluation of ForEach -parallel[/caption]

FYI ForEach is an Alias for ForEach-Object

PS C:\temp> Get-Alias ForEach

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           foreach -> ForEach-Object

I will need to test during some SharePoint Management and reporting things I have in the hopper.

Automate on!