Counting Number of Files - Fast!

Share |

Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Powershell Plus

13 Free SQL Tools from Idera

Free Ebook: Mastering Powershell


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?

Silence wrote re: Counting Number of Files - Fast!
on 11-11-2014 3:47 AM

Looks it get different count on my machine with command:

Get-ChildItem -Path $env:windir -File

$str1 = Get-ChildItem -Path $env:windir -File | Select-Object -ExpandProperty Name | Sort-Object

$str2 = Get-ChildItem -Path $env:windir -force | Where-Object { $_.PSIsContainer -eq $false } | Select-Object -ExpandProperty Name | Sort-Object

$str1.Count  # Output: 44

$str2.Count  # Output: 45

foreach($s2 in $str2)


   if($str1 -notcontains $s2)





After compared with the $str1 and $str2 on my machine, it output "WindowsShell.Manifest", looks the file such as "WindowsShell.Manifest" can't be detect by command:

Get-ChildItem -Path $env:windir -File

Silence wrote re: Counting Number of Files - Fast!
on 11-11-2014 3:59 AM

Found the issue, "WindowsShell.Manifest" was "Hide" on my machine, if I add "-force" to that command it works well now:

Get-ChildItem -Path $env:windir -File -Force

Copyright 2012 All rights reserved.