How to Remove All Empty Folders in PowerShell (With Example)


You can use the following syntax in PowerShell to list all empty folders in the current directory:

Dir -Directory -Recurse | Where-Object {$_.GetFileSystemInfos().Count -eq 0 }

You can then use the following syntax to recursively remove all empty folders in the current directory:

Get-ChildItem -Recurse -Force -Directory | 
  Sort-Object -Property FullName -Descending |
  Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } |
  Remove-Item -Verbose

Note that we use the Remove-Item cmdlet in the last line to delete the empty folders and we specify -Verbose so that PowerShell outputs the names of the folders that it deletes.

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

Example: How to Remove All Empty Folders in PowerShell

Suppose that we would like to delete all empty folders in our current directory.

We can first use the Dir statement to view all folders in the current directory:

Dir -Directory -Recurse

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

We can see that the current directory contains five folders and none of the folders have subfolders.

We can use the following syntax to first check if any of these folders are empty:

Dir -Directory -Recurse | Where-Object {$_.GetFileSystemInfos().Count -eq 0 }

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

This returns the names of two folders that are empty:

  • locations
  • regions

We can use the following syntax to remove these folders from the directory:

Get-ChildItem -Recurse -Force -Directory | 
  Sort-Object -Property FullName -Descending |
  Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } |
  Remove-Item -Verbose

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

PowerShell remove empty folders

The VERBOSE statement in the output tells us that both the regions and locations folders have been removed.

We can use the Dir statement once again to view all folders in the current directory:

We can see that the regions and locations folders have both been removed from the current directory.

Related Tutorials

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

PowerShell: How to Check if File is Empty
PowerShell: How to Check if String is Empty
PowerShell: How to Check if File Contains Specific String

Leave a Reply