Posts

Showing posts with the label Foreach-Object-Parallel

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. Le...