Count number of files in each subfolder, windows command line

Posted on

Problem :

There are many solutions for getting the total number of files within a directory using command line, but is there a way to get the number of files per sub directory using command line on Windows (powershell or CMD)?

Example:
We have the following structure:

root
  -> a
  -> b
  -> c
  -> d

The command requested would output something like:

a 5300
b 40
c 250
d 13

Solution :

There are many solutions for getting the total number of files within a directory using command line, but is there a way to get the number of files per sub directory using command line on Windows (powershell or CMD)?

Use the exact same solution, only put it within a “for each directory” loop.

  • In Cmd, use for /d to iterate over directories:

    for /d %a in (root*) do example_command_to_count_files_in_dir "%~a"
    
  • In PowerShell, use ForEach-Object (also known as %) to iterate over the results of Get-ChildItem (aka gci aka dir). Within the loop, $_ is used to reference each item.

    gci root | % { something_to_count_files $_ }
    

For example, whether you use the Measure-Object method or the @(dir) method from https://stackoverflow.com/a/14716609, you can just put the whole thing in the % script block:

dir root | % { $cout = (dir $_ -files | measure).count; echo "$_ has $count files"; }

dir root | % { $cout = @(dir $_).count; echo "$_ has $count items"; }

Of course, the same works with any other command that takes a directory name, whether it’s a PowerShell built-in cmdlet or an external .exe.

Leave a Reply

Your email address will not be published. Required fields are marked *