Updates to the Foreach-Object-Parallel function

One of the most used functions of the CPolydorou.General module is "Foreach-Object-Parallel". This function allows us to execute PowerShell commands in parallel. This is accomplished by using new PowerShell runspaces and the most recent enhancement allows us to feed the runspaces with parameters.

First, a quick example of the ForEach-Object-Parallel function.
PS C:\> (0..5) | ForEach-Object-Parallel -MaxThreads 2 -ScriptBlock {$_; Start-Sleep -s 2}

0
1
2
3
4
5

This does not seem that much but if you execute the above command, you'll notice that the numbers appear in pairs due to the MaxThreads being set to "2".

Each object passing the pipeline is being passed to the scriptblock of the Foreach-Object-Parallel function and can be accessed using the $_ variable.

The issue here is that since the scriptblock is executed on another PowerShell runspace, all the variables of the original runspace are not available.

Let's see how the enhancement allows us to pass more variables to the scriptblock. We'll start by creating a hashtable containing the names of the variables and their values.
PS C:\> $vars = @{ Name = "Firstname" LastName = "Lastname" }

We are going to use the same example but we are going to display the variables passed using the "-Parameters" parameter.
PS C:\> (0..5) |
    ForEach-Object-Parallel -MaxThreads 2 `
                            -Parameters $vars `
                            -ScriptBlock {
                                Write-Host "$Name - $LastName"
                                Start-Sleep -s 2
                             }
Firstname - LastName
Firstname - LastName
Firstname - LastName
Firstname - LastName
Firstname - LastName
Firstname - LastName

The variables in the hashtable are available in the scriptblock and can be accessed using their name.

Have fun!

Popular posts from this blog

Syslog Message Collection for OMS from sources that do not support the agent

Generating Alerts On OMS

How to Configure Message Forwarding on a Mailbox Level