Measure-Command: A speed comparison (Foreach vs. Foreach-Object)

Measure-Command measures how long a command or script takes to complete. This is particulary important for processing large amounts of data.


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


Now, let’s measure another command with Foreach-Object:

Measure-Command {0..1000000 | Foreach-Object $_}


8 seconds. Not bad.


If I do the same with foreach instead of Foreach-Object then I have to accept, that I’m much faster.

Measure-Command {foreach ($i in 0..1000000) {$i++}}


3,5 seconds. Microsoft explains why it is as it is:



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

Tagged as: ,

2 replies »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.