We help IT Professionals succeed at work.

vbscript to delete empty folders and sub folders in a directory, no prompts or msgbox

mark fillmore
on
Medium Priority
166 Views
1 Endorsement
Last Modified: 2020-01-19
Need a vbscript to delete all empty folders and sub folders in a directory.  No prompts or msgbox
Comment
Watch Question

Developer & EE Moderator
CERTIFIED EXPERT
Fellow
Most Valuable Expert 2013
Commented:
Hi Mark, I found your query interesting enough to write an article.  You can view it here https://www.experts-exchange.com/articles/33944/Use-VBScript-to-Silently-Remove-Empty-Folders.html.  If you have any questions, please let me know.

' 1) THE FOLDER TO START
startFolder = "C:\temp\ee\empty1"

' 2) VARIABLE TO HOLD ALL FOUND FOLDERS
txtFolderList = ""

' CREATE FILE SYSTEM OBJECT
Set fso = CreateObject("Scripting.FileSystemObject")

' 3) CALL SUBROUTINE THAT WILL RECURSIVELY GET ALL SUB FOLDERS
getSubfolders fso.GetFolder(startFolder)

' WHEN txtFolderList IS POPULATED
' IT WILL LOOK LIKE c:\path\folder[|]c:\path\folder[|]c:\path\folder
' 4) CREATE AN ARRAY USING splut and [|] TO SEPARATE

arrSubFolders = split(txtFolderList,"[|]")


' 5) LOOP THROUGH ARRAY BACKWARDS
' ALLOWS TO DELETE THE LAST FOLDER FIRST
intArraySize = LBound(arrSubFolders) 'array size
For x = UBound(arrSubFolders) to 0 step -1 'LOOP THROUGH FOLDERS BACKWARDS
	'RUN THE CLEAN ROUTINE FOR THE CURRENT SUBFOLDER
	clean arrSubFolders(x)
Next

'Wscript.Echo txtFolderList


' SUBROUTINE TO RECURSIVELY GET ALL SUB FOLDERS
Sub getSubfolders(Folder)

	'LOOP THROUGH ALL SUB FOLDERS
	For Each Subfolder in Folder.SubFolders
	
		if txtFolderList = "" then 'IF THIS IS THE FIRST ENTRY
			
			txtFolderList = Subfolder.Path 'ADD THE FIRST SUB FOLDER TO OUR txtFolderList
			
			else
			
			' CONTINUE TO ADD TO THE FIELD txtFolderList USING A DELIMINTER OF [|]
			txtFolderList = txtFolderList &"[|]"& Subfolder.Path
			
		end if
	
		'CALL getSubfolders INSIDE THE LOOP TO GET MORE SUB FOLDERS
		getSubfolders Subfolder
		
	Next
End Sub

' SUB ROUTIE TO CHECK IF FOLDER IS EMPTY
' DELETE FOLDER IF IT IS EMPTY
sub clean(strFolder)

	If fso.FolderExists(strFolder) Then 'MAKE SURE FOLDER EXISTS
	
		Set objFolder = fso.GetFolder(strFolder) 'CREATE FOLDER OBJECT
	  
		' CHECK THAT FOLDER IS EMPTY (REASON WE ARE GOING BACKWARDS)
		If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then 
		
			'DELETE FOLDER WHEN TRUE (EMPTY)
			fso.DeleteFolder strFolder
			
			
		end if
		
	End If

end sub


set fso = nothing

Open in new window

Peter ChanProblem resolver

Commented:
Hi,
Use method below to see if folder is empty:

    If Right(strPath, 1) <> "\" Then
        strPath = strPath & "\"
    End If
    If Dir(strPath & "*.*") = "" Then
        MsgBox "The folder doesn't contain (visible) files"
    Else
        MsgBox "The folder does contain (visible) files"
    End If
    

Open in new window

Here is example to remove folder:

    Dim FSO As Object
    Dim MyPath As String

    Set FSO = CreateObject("scripting.filesystemobject")

    MyPath = "C:\Users\Ron\Test"  '<< Change

    If Right(MyPath, 1) = "\" Then
        MyPath = Left(MyPath, Len(MyPath) - 1)
    End If

    If FSO.FolderExists(MyPath) = False Then
        MsgBox MyPath & " doesn't exist"
        Exit Sub
    End If

    FSO.deletefolder MyPath

Open in new window

Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Here's a simple VBS that gets the job done, just adjust the path to the base folder (which will be deleted if empty) and it will process the tree below it.

Const strBaseDir = "C:\Temp"

set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

RemoveFolder objFSO.GetFolder(objFSO.GetAbsolutePathname(strBaseDir))

Sub RemoveFolder(objFolder)
    For Each objSubFolder In objFolder.Subfolders
        RemoveFolder objSubFolder
    Next
    If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
        objFolder.Delete
    End If
End Sub

Open in new window


»bp
CERTIFIED EXPERT
Top Expert 2014

Commented:
Does the solution need to be VBScript or can it be Powershell?
Scott FellDeveloper & EE Moderator
CERTIFIED EXPERT
Fellow
Most Valuable Expert 2013

Commented:
Bill,that is an excellent solution. I over thought the process by deleting the deeper most folders first.
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Thanks Scott, appreciate the feedback.  My recursive approach will in deed drive down to the lowest "leaves" on any folder branch, since a roll-up approach is needed for the delete to work well.  Meaning if a folder has subfolders that have subfolders, we want to get the deepest children first delete the empties, then back up to the parent after all it's child directories have been dealt with, and if it becomes empty after that then we want to remove it when we get back up to it.

That's why we do the For Each subfolder loop first in the recursive subroutine, and then after all children are processed we check if this folder is empty and remove it.


»bp
mark fillmoreoperations manager

Author

Commented:
Scott the comments (and especially the article) were extremely helpful.  I was way overthinking it.