PowerShell: How to Recursively Count Files in Subfolders


Often you may want to use PowerShell to recursively count the number of files in each subfolder of a particular directory.

You can use the following syntax to do so:

Dir -Recurse -Directory |
  ForEach-Object {
    Write-Host $_.FullName (Dir $_.FullName | Measure-Object).Count
}

This particular example will return the full path to each subfolder in the current directory along with the total number of files in each subfolder.

Here is what the various commands do:

  • Dir -Recurse -Directory: Retrieve all subfolders in current directory
  • ForEach-Object: Perform a specific task on each subfolder
  • Write-Host $_.FullName: Print the full path to the current subfolder
  • (Dir $_.FullName | Measure-Object).Count: Return the total count of files in the current subfolder

The following example shows how to use this syntax in practice.

Example: Use PowerShell to Recursively Count Files in Subfolders

Suppose that our current directory has the following path:

  • c:\users\bobbi\data1

Suppose that we would like to count the total number of files in each subfolder of our current directory.

Before we do so, we can first use the tree command to view the folder structure of our current directory:

We can see that our current directory has the following structure:

├───athletes
├───coaches
└───managers
    ├───admin
    └───roster

There are three folders inside of the data1 folder named athletes, coaches and managers.

Within the managers folder, there are two folders named admin and roster.

We can use the following syntax to count the total number of files in each of these subfolders:

Dir -Recurse -Directory |
  ForEach-Object {
    Write-Host $_.FullName (Dir $_.FullName | Measure-Object).Count
}

The following screenshot shows how to use this syntax in practice:

PowerShell count files in subfolders

The output displays the full path to each subfolder along with the total file count of each subfolder.

For example, we can see:

  • c:\users\bobbi\data1\athletes contains 2 total files.
  • c:\users\bobbi\data1\coaches contains 1 file.
  • c:\users\bobbi\data1\managers contains 3 total files.

And so on.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Sort Files in Folder by Size
PowerShell: How to Get Folder Size in GB
PowerShell: How to List Files in Directory by Date
PowerShell: How to Get Most Recently Modified File in Directory

Leave a Reply