Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Quick PowerShell snippet to show ForEach -parallel differences

A colleague shared a blog post regarding the use of the Foreach loops with the parallel parameter in PowerShell (  http://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 workflow1

{
    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
workflow1 NumberOfIterations 50 Delay 150
# Output in milliseconds
50 iterations with a 150 milliseconds delay
serial :
7985.0853
parallel :
520.4536

PowerShell Script for quick evaluation of ForEach -parallel

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!

Share the post

Quick PowerShell snippet to show ForEach -parallel differences

×

Subscribe to Msdn Blogs | Get The Latest Information, Insights, Announcements, And News From Microsoft Experts And Developers In The Msdn Blogs.

Get updates delivered right to your inbox!

Thank you for your subscription

×