The PowerShell pipeline is a practial tool in the shell. But if you are writing scripts or workflows, avoid the pipeline! It will increase the running time of your script/workflow.
Run to following script on your machine to see the difference:
1 2 3 4 5 6 7 8 9 10 11 |
Measure-Command { 1..1000000 | ForEach-Object { $i = $_ * $_ } } Measure-Command { foreach($number in 1..1000000) { $i = $number * $number } } |
On my machine, the operation with the foreach-object (pipeline) took 4.7s longer than a simple foreach.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Days : 0 Hours : 0 Minutes : 0 Seconds : 5 Milliseconds : 197 Ticks : 51970778 TotalDays : 6.01513634259259E-05 TotalHours : 0.00144363272222222 TotalMinutes : 0.0866179633333333 TotalSeconds : 5.1970778 TotalMilliseconds : 5197.0778 Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 521 Ticks : 5219910 TotalDays : 6.0415625E-06 TotalHours : 0.0001449975 TotalMinutes : 0.00869985 TotalSeconds : 0.521991 TotalMilliseconds : 521.991 |
Another advantage is the readability of your code: while using the pipeline, the name of the control variable is given ($_), you can choose a meaningful name in a simple foreach (e.g. foreach ($process in Get-Process)).