Counting Number of Files - Fast!

Share |

Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus

Admin Guide to PowerShell Remoting

Mastering PowerShell eBook

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:


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!

Posted Jun 13 2013, 06:00 AM by powershelltips


barinv wrote re: Counting Number of Files - Fast!
on 06-13-2013 12:51 PM

Wouldn't this be easier?

$files = Get-ChildItem -Path $env:windir -File


thulasi39 wrote re: Counting Number of Files - Fast!
on 06-14-2013 10:10 AM


What's the purpose of using $_.PSIsContainer?

If i use get-member for anyfile, i get PSIsContainer as a Noteproperty. But how to get more help on this?

Copyright 2012 All rights reserved.