Ok, if you use your favourite search engine to look up a recursive deletion of empty folders, you will more than likely come up with a lot of results. I did. However by the end of the first page, I hadn’t found what I needed, so made up my own.
The special bits about this script:
- It forces you to use cscript and the command line, meaning that you won’t have to keep clicking OK to the prompts.
- It checks if there are any thumbs.db or desktop.ini files in the folders first, as these would otherwise stop the deletion.
- It tells you at the end if there were any errors.
Nothing particularly ground breaking, just more useful to me.
So, here it is. My advice – when running the script run it and pipe the results to a file – that way you can quickly search the file for the word ‘Error’ to see what didn’t work. For example:
cscript C:\Scripts\DeleteEmptyFolders.vbs > C:\Scripts\Results.txt
This script now includes the modification suggested below by Andrew.
'Script to delete all empty folders within a given directory. 'Recursively searches through to make sure that folders that just contain empty folders are also removed. 'Also removed desktop.ini and thumbs.db files if they exist to accurately remove empty folders. 'Craig Tolley 'Version 1.0 - 27/12/2013 - Initial Release 'Version 1.1 - 26/02/2015 - Modified following feedback to check subfolders before checking the parent 'Version 1.2 - 08/03/2017 - Add in missing RemoveDesktopIni and RemoveThumbsDb Flags 'Version 1.3 - 13/02/2018 - Corrected Select statement to properly set RemoveThumbsDb and RemoveDesktopIni ' '------------------- START SCRIPT ------------------- Option Explicit On Error Resume Next 'Check we are running from the command line and using cscript. If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then WScript.Echo("You must use cscript and run this script from the command line." & Chr(13) & "e.g cscript.exe DeleteEmptyFolders.vbs") WScript.Quit End If 'Define some variables and bits. Dim objFSO, strFolderPath, intErrorCount, RemoveThumbsDb, RemoveDesktopIni Set objFSO = CreateObject("Scripting.FileSystemObject") intErrorCount = 0 'Ask user for the folder to tidy up. Check they entered something and that what they entered is actually a valid folder. strFolderPath = InputBox("Enter the path of the directory to clean up") strFolderPath = Trim(strFolderPath) If Len(strFolderPath) = 0 Then WScript.Echo "No path entered. Exiting" WScript.Quit End If If (objFSO.FolderExists(strFolderPath)) = False Then WScript.Echo "The path entered is either invalid or cannot be found. Please check and try again." WScript.Quit End If ' Ask user whether to remove any desktop.ini files if they are found Select Case (MsgBox ("Should the script remove desktop.ini files if they are found? Not removing them may result in otherwise empty folders being left.", vbYesNo + vbQuestion, "Remove desktop.ini files?")) Case vbYes RemoveDesktopIni = True Case vbNo RemoveDesktopIni = False End Select ' Ask user whether to remove any thumbs.db files if they are found Select Case (MsgBox ("Should the script remove thumbs.db files if they are found? Not removing them may result in otherwise empty folders being left.", vbYesNo + vbQuestion, "Remove thumbs.db files?")) Case vbYes RemoveThumbsDb = True Case vbNo RemoveThumbsDb = False End Select 'Run the recursive cleanup RecursiveDeleteEmptyFolders strFolderPath, RemoveDesktopIni, RemoveThumbsDb 'Give the user back some information. WScript.Echo "--------------------------------------------------------------------" WScript.Echo "Finished Cleanup of " & strFolderPath If intErrorCount > 0 Then WScript.Echo "There were " & intErrorCount & " errors during the operation" WScript.Echo "--------------------------------------------------------------------" 'Sub to recursively delete all empty folders. Sub RecursiveDeleteEmptyFolders(ByVal strDirectory, ByVal RemoveDesktopIni, ByVal RemoveThumbsDb) On Error Resume Next Dim objFolder, objSubFolder Set objFolder = objFSO.GetFolder(strDirectory) WScript.Echo "Checking Folder: " & strDirectory & ". Contains " & objFolder.Files.Count & " files and " & objFolder.SubFolders.Count & " folders." 'If the RemoveDesktopIni or RemoveThumbsDB Flag is set to True then remove any files called Desktop.ini or thumbs.db If objFSO.FileExists(strDirectory & "\desktop.ini") And RemoveDesktopIni = True Then objFSO.DeleteFile(strDirectory & "\desktop.ini") If Err Then WScript.Echo "Error deleting:" & strDirectory & "\desktop.ini" & " - " & Err.Description intErrorCount = intErrorCount + 1 Err.Clear End If End If If objFSO.FileExists(strDirectory & "\thumbs.db") And RemoveThumbsDb = True Then objFSO.DeleteFile(strDirectory & "\thumbs.db") If Err Then WScript.Echo "Error deleting:" & strDirectory & "\thumbs.db" & " - " & Err.Description intErrorCount = intErrorCount + 1 Err.Clear End If End If 'Check if there are any subfolders, and if so go through each of those recursively deleting them If objFolder.SubFolders.Count > 0 Then For Each objSubFolder in objFolder.SubFolders RecursiveDeleteEmptyFolders objSubFolder.Path, RemoveDesktopIni, RemoveThumbsDb Next End If 'Now check if the folder contains any files. If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then 'Check that the folder name does not begin with a tildeand if it does not then delete it If Left(objFolder.Name,1) <> "~" Then WScript.Echo "Deleting: " & objFolder.Path objFolder.Delete If Err Then WScript.Echo "Error deleting:" & objFolder.Name & " – " & Err.Description intErrorCount = intErrorCount + 1 Err.Clear End If End If End If End Sub
Hi Craig,
the Select Case statements for removing “desktop.ini” and “thumbs.db” check vbYes twice and not vbNo!
So you will always remove them.
Best Regards
Thomas
Thanks Thomas, now fixed.
culd you simplify it for a beginner,,,,,,lots of foldrs have turned up on my start up screen,,,dont kow where fom but ive deleted them all manually and they have comeback
Hi, If the folders keep coming back then this script will not help you. You will need to find out what is repeatedly creating the folders first.
2017 and someone still need this script! :-)
I use some of your code and some others elsewhere to make something more useful. It’s easily readable and configurable for anything else.
The only problem is to delete multiple empty folders. This script needs to be run multiple times. In my case it’s not a problem since the script will run once a day in Task Scheduler and if there’s a few empty folders left, it’s really no big deal because the next run will delete them.
‘This script will delete, recursively:
‘ – All desktop.ini files
‘ – All Thumbs.db files
‘ – All files older than “olderThanDays”
‘ – All empty folders
‘Run it multiple times to delete multiple empty folders
‘Example: Script needs to be run 3 times to delete all empty folders for C:\empty1\empty2\empty3
Option Explicit
‘Configurable variables
Dim olderThanDays, folder
olderThanDays = 365
folder = “C:\somewhere\you\want\to\delete”
‘Run the script
Dim objFSO, objFolder, objSubFolder, objFile
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objFolder = objFSO.getFolder(folder)
Call Search(objFolder)
Sub Search(objFolder)
For Each objFile In objFolder.files
If dateDiff(“d”,objFile.dateLastModified,Now) > olderThanDays Then
objFile.Delete
ElseIf strcomp(objFSO.GetFileName(objFile), “desktop.ini”) = 0 Then
objFile.Delete
ElseIf strcomp(objFSO.GetFileName(objFile), “Thumbs.db”) = 0 Then
objFile.Delete
End If
Next
For Each objSubFolder In objFolder.SubFolders
If objSubFolder.Files.Count = 0 And objSubFolder.SubFolders.Count = 0 Then
objSubFolder.Delete
Else
Search(objSubFolder)
End If
Next
End Sub
I’m not sure I follow what you are saying. I have just tested the copy of the script in the blog post, and it works, recursively deleting all empty folders in one go.
Can you elaborate on the problem that you are having?
Great script, just what I was looking for, thanks for sharing. I have 1 question though,
why are you not deleting folders that start with “~”?
Also, just a minor comment, in the script you have a comment that says ‘If the RemoveDesktopIni or RemoveThumbsDB Flag is set…… but the script does not set those 2 flags, the script will always delete these files.
I exclude ~ folders as they are snapshot directorys on our storage system, so are not writeable.
I have also now added in the missing flags and questions to the functions. Thanks for pointing that out.
A little late to the game I know. First off I want to say this is a nice script BUT it could be a little better. Say I have the following structure
cwd
-folder a
—folder a1
—folder a2
-file1
-file2
Currently your code will delete folder a1 and a2, BUT leave folder a, even though it will eventually become empty. If you move the subdirectory recursive call to before the file.count it will process all the subfolders first (A depth first search) and in this case it will delete a1,a2 then a!! here is the change. The code is nearly identical, I just moved some things around
‘ check if there are any subfolders.
If objFolder.SubFolders.Count 0 Then
‘Subfolders found, so go through each of those.
For Each objSubFolder in objFolder.SubFolders
RecursiveDeleteEmptyFolders objSubFolder.Path
Next
End If
‘Now check if the folder contains any files.
If objFolder.Files.Count = 0 Then
if objFolder.SubFolders.Count = 0 Then
‘Check that the subfolders do not begin with a tilde, and if they do not, delete the folder.
If Left(objFolder.Name,1) “~” Then
WScript.Echo “Deleting: ” & objFolder.Path
objFolder.Delete
If Err Then
WScript.Echo “Error deleting:” & objFolder.Name & ” – ” & Err.Description
intErrorCount = intErrorCount + 1
Err.Clear
End If
End If
end if
Else
Hi Andrew,
You are totally right, and it turns out I had changed the copy of the script on my computer to basically what you had done and never updated the copy on my site! Thanks for the feedback.
Andrew, your modification is a good one. If your intention was to instruct you succeeded.
However, if your intention was to make this script useful for others, you might have provided the full routine rather than just the snippet which illustrates the logic. That way people wouldn’t have had to cut and paste into the original risking syntax errors.
Thanks Chris, you are right in what you say. I would hope that people would find the time to learn the language and be able to fix the errors, but for something utilitarian such as this I can see that you would just want to copy and paste and it would work.
Based on that, I have updated the main code in the post and credited Andrew with the change.