Possible to execute ForEach-Object commands in Parallel

Viewed 7159

I have been attempting to execute parallel commands on data (such as a list of Server Names) that is imported via CSV and called by ForEach-Object. I have found that foreach has a parallel method but it appears that ForEach-Object does not. I am concerned about good performance as I hit multiple servers to read log data, and have the following options:

1) PowerShell Workflow 
2) PowerShell Background Job 
3) Invoke-Command

When I tried option 3, it failed as I tried to send arguments via -ArgumentList, but it didn't seem to like the variables I was pushing from the CSV in the form of:

$($_.'CSVColumnValue')

Is it possible to execute commands in parallel using ForEach-Object, and if so, what is the recommended method to achieve this?

2 Answers

As far as invoke-command goes, you would need to use the 'using' scope to access local variables:

$a = 'hi there'
invoke-command comp001 { echo $using:a }

Or to pipe something in:

1,2,3 | invoke-command comp001 { echo $input } 

-argumentlist only works if there's a param defined in the scriptblock. The docs aren't good on this point.

$a = 'hi'
invoke-command comp001 { param($a) echo $a } -ArgumentList $a

Unless you use args:

invoke-command comp001 { echo $args[0] } -ArgumentList $a

Powershell 7 preview 3 actually has a multi-thread "foreach-object -parallel":

 1..5 | ForEach-Object -Parallel { sleep 10; 'done' }
Related