Counting Files Efficiently (Part 1)

A quick and dirty approach for counting files could be this:

(Get-ChildItem -Path c:\windows).Count

However, it would produce some memory load because all files would have to be accumulated in memory before Count property would retrieve the number of objects. When you search recursively, this can add up.

A much less resource intensive approach uses Measure-Object like this:

(Get-ChildItem -Path c:\windows | Measure-Object).Count

Here, the number of items are retrieved using a stream, so PowerShell does not have to store all files in memory.

Twitter This Tip! ReTweet this Tip!

  • May be more memory efficient, but at the sacrifice of speed.

    Your example was almost 45% slower, reducing to ~14% slower with -Recurse.