How to Remove Empty Folders/Directories recursively with PowerShell

As part of System Admin, you will have control of more servers and there may be hundreds of empty folders as junk files which may take up your hard disk. While the junk files occupy disk and it became more Junk in the servers so it became critical to maintaining the important files.

The empty folders don’t take up disk space, but to organize your data better, you may want to trim them every once in a while. If you feel to manually delete empty folders then it will need to routine and time consuming manual work. So we below PowerShell script will help you t to query and delete all empty folders and subfolders.

The following PowerShell command-line deletes empty folders, located under the specified base folder recursively.

STEP #1: Get the recursive child items

First, we need to get the child items from the source path ie., C:\dotnet-helpers\TEMP Folder

//gci alias of Get-ChildItem
gci “C:\dotnet-helpers\TEMP Folder” -r

STEP #2: Fetch all the empty folders

To filter the folders/directories available in the current context, the following property can use $_.psiscontainer. It will return a boolean, indicating whether the current object is a directory or not.

PSIsContainer retrieves an array of strongly typed FileSystemInfo objects representing files and subdirectories of the current directory. The count is not 0, it doesn’t exist at all meaning that the directory is empty or holds other empty folders

(gci “C:\dotnet-helpers\TEMP Folder” -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0}

OUTPUT

STEP #3: Remove the collection of Empty folders.

Finally, use the remove-item cmdlet to remove all the empty folder/directories 

(gci “C:\dotnet-helpers\TEMP Folder” -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | remove-item

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.