Deleting Empty Folders

For the sake of this post, let's assume that you have a directory that contains some empty folders you want to get rid of. How the empty folders got there isn't important; all that matters is that you have some and you want to get rid of them.

A few years ago, I created the following script (starting from a sample I found in the Script Center on TechNet) to recursively enumerate a folder structure, identify any empty folders, and subsequently delete them.

Option Explicit

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

Dim strPath
strPath = WScript.Arguments(0)

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim objFolder
Set objFolder = fso.GetFolder(strPath)

DeleteEmptyFolders objFolder

Sub DeleteEmptyFolders(folder)
Dim subfolder
For Each subfolder in folder.SubFolders
DeleteEmptyFolders subfolder

If folder.SubFolders.Count = 0 And folder.Files.Count = 0 Then
WScript.Echo folder.Path & " is empty"
fso.DeleteFolder folder.Path
End If
End Sub

As you can see, there's really nothing complex here. Nevertheless I still find it to be a very useful script from time to time, so I thought I should share it. I used it this morning and it occurred to me that I should throw it up on the blog.

Just be sure to run it with CScript -- and not the default WScript -- or you'll find the WScript.Echo messages rather frustrating.

Comments (0)

Skip to main content