Counting Files Efficiently (Part 1)

by Sep 22, 2017

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!