Wednesday, June 19, 2013

Counting no. of Files


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

    And here's the commands 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

   Using .Net:

[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