How to Remove Empty Folders Automatically in Windows

Over time, hundreds of empty folders and junk files may take up your hard disk. While the junk files occupy disk space and can be cleaned up using Disk Cleanup or Storage settings, the empty directories remain.

The empty folders don’t take up disk space, but to organize your data better, you may want to prune them every once in a while.

This article discusses different methods to find and remove empty folders on your computer.

How to Find and Remove Empty Folders in Windows?

An empty folder or directory is one which has no file or sub-directory in it. Empty folders don’t take any disk space, but too many of them can be a nuisance. To find and remove them, use one of the methods below.

Important: Running an automated tool or batch file to delete empty folders in the entire system drive recursively is usually not recommended. This is because some programs may fail to work and throw a bizarre error when it finds an essential folder missing. As always, the standard warning applies. Be sure to have appropriate backups preferably on an external drive, before manipulating with the file system or the Windows registry.

RELATED: Find and delete 0-byte files recursively in a folder in Windows

Let’s start off with a neat GUI tool, followed by native command-line and scripting methods.

1. Remove empty folders using the “Find Empty Files-n-Folders” utility

Find Empty Files-n-Folders is an excellent tool that can find and delete empty files (0-byte) and empty folders recursively under a folder tree.

Download Find Empty Files-n-Folders (600KB installer) from Ashisoft.com.

Select the folder and click Scan Now.

remove empty folders in windows

The tool will list empty files and folders in separate tabs.

Click Mark all Folders and then click Delete Folders.

remove empty folders in windows

Similarly, to delete the 0-byte files in the selected folder tree, click on the Empty Files tab.

Ashisoft.com has other awesome tools that you can check out!


2. Remove empty folders using “for” and “rd” commands

You can use the Command Prompt internal commands for and rd to enumerate the list of folders and delete the empty ones.

  1. Press & hold the Shift key, right-click on a folder and click Open command window here.This opens Command Prompt at the current folder location, which can also verify in the console.Note: You must make sure that you run the following command from the exact parent folder path where you need to find and remove empty sub-folders.
  2. Once you’re in the desired directory in the Command Prompt, run this command-line:
    for /f "delims=" %i in ('dir /s /b /ad ^| sort /r') do rd "%i" 2>NUL

    remove empty folders using for and rd - batch command

    This deletes all the empty directories across sub-directories from the base folder path, including nested empty folders.

The above command-line is courtesy of Raymond Chen of Microsoft, via his blog The Old New Thing. In this post, Raymond’s command-line has been slightly modified so that it also deletes folder names containing space(s).

How does the command work

The above command lists all the sub-directories (recursively) in the current base path, and sorts the list (sort /r) in reverse order. The reverse order sort is to make sure that the enumeration is done bottom-up. This important for deleting empty directories, as you have to remove the subdirectories before you remove the parent.

Then it attempts to remove the list of directories (in reverse sort order) using the RD command. If a directory is not empty, it proceeds on to the next directory and so on. The 2>NUL command ensures that the the “directory not empty” output text is suppressed.

The only disadvantage of the above method is that it’s not helpful if you simply want to find empty folders without deleting them. If you want to find the list of empty folders, use the command-line in the paragraph below, or follow any other method described in this article.

Find empty folders, but don’t delete

To only find the empty folders without deleting them, use this command-line syntax:

for /r "D:\uploads\2019" /d %F in (.) do @dir /b "%F" | findstr "^" >nul || echo %~fF

It shows you the output containing the list of empty directories.

Let’s say you have empty nested folders like this:

C:\1
└───2
    └───3
        └───4

Running the above command lists only the deep most empty folder → 4. Technically, it’s correct because a folder can’t be considered empty if a sub-folder or a file exists in it.


3. Find and remove empty folders using Robocopy command

Robocopy is a powerful built-in file copy tool which has a lot of advanced features. We’ve covered Robocopy in the article Compare the Contents of Two Folders in Windows.

Let’s assume you have a folder named cars which contains several sub-folders of which some are empty. We’re going to delete the empty ones using Robocopy.

hand point iconThe trick here is to use the Robocopy move command, passing the exact same folder path for both source as well as destination.

  1. Open a Command Prompt window
  2. Type the following command and press ENTER:
    robocopy "d:\automobile rates\cars" "d:\automobile rates\cars" /S /move

    The most important thing to note here is that the source and destination paths are (deliberately) the same. The /S parameter instructs Robocopy not to move empty folders to the “destination” path. As we’ve mentioned the same paths for source and destination, Robocopy will simply delete the empty folders due to the presence of /S switch.

    robocopy remove empty folders

The empty folders in the chosen path are now cleared.

Want to find empty folders but not delete them?

You can use the /L (list-only) command-line argument with Robocopy so that it only carries out a dry-run instead of performing the actual copy/move operation.

/L :: List only – don’t copy, timestamp or delete any files.
/MOVE :: MOVE files AND dirs (delete from source after copying).
/S :: copy Subdirectories, but not empty ones.

robocopy delete empty folders - list -dryrun

You can see the number of files in a column hear the folder path. The 0s mean that those folder have no files.

Let’s put this command to a real test!

My %APPDATA% folder is full of empty folders added by programs which are obsolete.

appdata roaming folder contents

Before the cleanup, the Appdata\Roaming folder had 681 folders, as seen in the folder properties.
remove empty folders - before

I opened the Command Prompt, and ran the following command:

robocopy "%appdata%" "%appdata%" /S /MOVE

Note: %appdata% environment variable translates to C:\Users\{username}\AppData\Roaming folder. You can use the full folder path or the equivalent environment variable with Robocopy. Either is fine.

robocopy remove empty folders - appdata roaming

It has successfully removed 94 empty folders in my %APPDATA% folder and sub-folders.

remove empty folders - after



Editor’s note: In the command-line output below the statistics section, the following error appeared:

“ERROR 32 (0x00000020) Deleting Source Directory C:\Users\ramesh\AppData\Roaming\
The process cannot access the file because it is being used by another process.”

robocopy remove empty folders - error

Because we’ve instructed Robocopy to move (/MOVE) the %APPDATA% directory, the tool was trying to cleanup the “source” folder after “moving” it to the destination. It couldn’t, as %APPDATA% is a special folder. The error doesn’t occur when used a directory path that’s not a special folder. As everything went on fine, I simply ignored the (trivial) error.


4. Find and Remove empty folders using PowerShell

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

  1. Start PowerShell and type the following command:
    (gci "folderpath" -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | remove-item

    Replace “folderpath” with the base folder location. For example, I’m specifying the Roaming folder here:

    (gci "C:\Users\ramesh\AppData\Roaming" -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | remove-item

    powershell remove empty folders recursively

    This deletes all the empty sub-folders under my %appdata% folder recursively and doesn’t show any output, unless it encounters any error(s).

Note that the above PowerShell command clears only the last level of empty nested folder. For example, let’s say you have empty nested folders like this:

C:\1
└───2
    └───3
        └───4

Running the above command clears the deep most empty folder → 4. Running the script again will clear another level of a nested folder (3), and so forth.

You can use the PowerShell script at Svendsen Tech PowerShell Wiki to work with nested folders.

Alternately, you can use the next method, a Windows Scripting solution to clear all empty folders including nested ones recursively.

Find empty folders, but don’t want to delete them?

Want to get the list of empty folders, but don’t want to delete them? Use this command-line example instead:

(gci "C:\Users\ramesh\AppData\Roaming" -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | select FullName | Out-GridView

powershell remove empty folders recursively

The command outputs the list of empty folders with full paths to a grid view control.

powershell find empty folders list output grid view

Tip: In the grid view, you can select all and copy the selection by pressing Ctrl + C

It’s a good idea to preview the list before running the command to delete the folders.


5. Find and Remove empty folders using Windows Scripting

Microsoft employee Jeremy Jameson wrote a VBScript that deletes empty folders recursively. I’ve added more lines in the script so it force deletes empty read-only directories, output the aggregated list of empty folders. It also outputs the list of empty folders that could not be deleted, along with corresponding the error description.

The script is capable of deleting nested empty directories across sub-folders.


Option Explicit

If (WScript.Arguments.Count <> 1) Then
   WScript.Echo("Usage: cscript DeleteEmptyFolders.vbs {path}")
   WScript.Quit(1)
End If

Dim strPath : strPath = WScript.Arguments(0)
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim objFolder : Set objFolder = fso.GetFolder(strPath)
Dim sDelList, sDelErr, sFolderPath
Dim iCnt
iCnt = 0

DeleteEmptyFolders objFolder

Sub DeleteEmptyFolders(folder)
   Dim subfolder

   On Error Resume Next
   'Skip errors when accessing Junctions, etc.
   For Each subfolder In folder.SubFolders
      DeleteEmptyFolders subfolder
   Next
   On Error Goto 0
   
   If folder.SubFolders.Count = 0 And folder.Files.Count = 0 Then
      sFolderPath = folder.Path
      On Error Resume Next
      fso.DeleteFolder folder.Path, True
      If Err.number <> 0 Then
         sDelErr = sDelErr & Err.number & ": " & Err.description & _
            vbCrLf & sFolderPath & vbCrLf & vbCrLf
      Else
         sDelList = sDelList & vbCrLf & sFolderPath
     iCnt  = iCnt + 1
      End If        
      On Error Goto 0
   End If    
End Sub

If sDelList = "" And sDelErr = "" Then
   WScript.Echo "No Empty folders found under the " & _
    """" & strPath & """" & " tree"
   WScript.Quit
End If

If sDelList <> "" then sDelList = "List of empty folders deleted" & vbCrLf _
   & String(38,"-") & vbCrLf & sDelList & vbCrLf & _
    vbCrLf  & "Total: " & iCnt & " folders deleted."

If sDelErr <> "" then sDelErr = "These folders could not be deleted" & _
   vbCrLf & String(45,"-") & vbCrLf & sDelErr

WScript.Echo sDelList & vbCrLf & vbCrLf & sDelErr

Copy the above code to Notepad and save the file with a .vbs extension, say delempty.vbs.

You can run the script using 2 ways:

via Command Prompt, by running:

cscript.exe delempty.vbs "folder_path"

find and remove empty folders

via GUI, by running:

wscript.exe delempty.vbs "folder_path"

via the Send To menu

You can create a shortcut to the script in your SendTo folder, and name it as Delete Empty Folders.

remove empty folders

Then, right-click on a folder where you want to delete empty sub-folders recursively → click Send To → click Delete Empty Folders in the Send To menu.

You’ll see the list of empty folders deleted and the total, and folders which couldn’t be deleted with the respective error codes displayed.

find and delete empty folders - vbscript

That’s it! If you know any other methods to remove empty folders in Windows, let’s know that in the comments section below.


One small request: If you liked this post, please share this?

One "tiny" share from you would seriously help a lot with the growth of this blog. Some great suggestions:
  • Pin it!
  • Share it to your favorite blog + Facebook, Reddit
  • Tweet it!
So thank you so much for your support, my reader. It won't take more than 10 seconds of your time. The share buttons are right below. :)

About the author

Ramesh Srinivasan founded Winhelponline.com back in 2005. He is passionate about Microsoft technologies and he has been a Microsoft Most Valuable Professional (MVP) for 10 consecutive years from 2003 to 2012.

3 thoughts on “How to Remove Empty Folders Automatically in Windows”

  1. Your “Remove empty folders using “for” and “rd” commands” code is broken. It doesn’t work.
    The original code by Raymond Chen works fine though.

    Reply
  2. 5. Find and Remove empty folders using Windows Scripting

    Option Explicit

    If (WScript.Arguments.count = 0) Then
    WScript.Echo(“Usage: cscript DeleteEmptyFolders.vbs {path}”)
    WScript.Quit(1)
    End If


    ****Fixed****

    Reply
    • @Eiríkur: WordPress seems to have stripped off the special characters in that code. I’ve now fixed the formatting. Thanks for your comment.

Leave a Comment