Counting Number of Files – Fast!

by Jun 13, 2013

If you need to know the number of files in a folder, there are different approaches with different advantages and disadvantages.

The first one is using plain cmdlets and determines the number of files in the Windows folder:

Get-ChildItem -Path $env:windir -Force |
  Where-Object { $_.PSIsContainer -eq $false } |
  Measure-Object |
  Select-Object -ExpandProperty Count

The second one does the same but uses .NET methods and is shorter and is about 20x as fast:

[System.IO.Directory]::GetFiles($env:windir).Count

To test for yourself, use Measure-Command.

And here's the code to count the number of files recursively, including all subfolders:

Get-ChildItem -Path $env:windir -Force -Recurse -ErrorAction SilentlyContinue |
  Where-Object { $_.PSIsContainer -eq $false } |
  Measure-Object |
  Select-Object -ExpandProperty Count

[System.IO.Directory]::GetFiles($env:windir, '*', 'AllDirectories').Count

Again, the .NET approach is much faster, but it has one severe disadvantage. Whenever it comes across a file or folder it cannot access, the entire operation breaks. The cmdlets are smarter. Get-ChildItem and its parameter -ErrorAction can ignore errors and continue with the remaining files.

Twitter This Tip! ReTweet this Tip!