Measure-Command measures how long a command or script takes to complete. This is particulary important for processing large amounts of data.
Measure-Command
In this first example, I measure the command Get-ChildItem by searching all files with the file name Windows.
Measure-Command {Get-Childitem -Path c: -File -Recurse -ErrorAction SilentlyContinue | Where-Object Name -eq "Windows"}
It took about 44 seconds. That’s fast. I have a SSD.
The Comparison
Foreach-Object
Now, let’s measure another command with Foreach-Object:
Measure-Command {0..1000000 | Foreach-Object $_}
8 seconds. Not bad.
Foreach
If I do the same with foreach instead of Foreach-Object then I have to accept, that I’m much faster.
$i=0 Measure-Command {foreach ($i in 0..1000000) {$i++}}
3,5 seconds. Microsoft explains why it is as it is:
Conclusion
Foreach consumes more memory, but it’s faster. All objects are stored in memory. With Foreach-Object the objects are processed one after another and the results for each object, which goes through the pipe is output instantly. Anyway, my favourite is Foreach-Object. 😉
More: https://www.pluralsight.com/blog/tutorials/measure-powershell-scripts-speed.
Categories: PowerShell
2 replies »