How to Count Folders in PowerShell (With Examples)


Often you may want to use PowerShell to count the number of folders in a directory.

You can use the following methods to do so:

Method 1: Count Number of Folders in Current Directory

(Get-ChildItem -Directory -Force).Count

This particular example will return the total count of folders in the current directory.

Method 2: Count Number of Folders and Subfolders in Current Directory

(Get-ChildItem -Directory -Recurse -Force).Count

This particular example will return the total count of folders and all subfolders in the current directory.

Here is what the various commands do:

  • Get-ChildItem: Retrieve all items in current directory
  • -Directory: Only retrieve folders and not files
  • -Recurse: Recursively retrieve all subfolders within each folder
  • -Force: Retrieve hidden files as well

The following example shows how to use each method in practice.

Example: How to Count Folders in PowerShell

We can use the tree command to display the folder structure of our current directory in PowerShell:

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

├───nba_data
├───nfl_data
└───nhl_data
    ├───new_data
    └───old_data

There are three folders in the current directory named nba_data, nfl_data, and nhl_data.

Within the nhl_data folder, there are two folders named new_data and old_data.

We can use the following syntax to count the number of folders just in the current directory:

(Get-ChildItem -Directory -Force).Count

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

PowerShell count folders in directory

The output tells us that there are 3 total folders in the current directory.

We can also use the following syntax to count the total number of folders and subfolders in the current directory:

(Get-ChildItem -Directory -Recurse -Force).Count

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

PowerShell count folders and subfolders in directory

The output tells us that there are 5 total folders and subfolders in the current directory.

By including the -Recurse parameter, we are able to recursively move through each folder and count any subfolders within each folder.

Note: You can find the complete documentation for the Get-ChildItem cmdlet in PowerShell here.

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