mark fillmore
asked on
vbscript to delete empty folders and sub folders in a directory, no prompts or msgbox
Need a vbscript to delete all empty folders and sub folders in a directory. No prompts or msgbox
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
»bp
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
»bp
Does the solution need to be VBScript or can it be Powershell?
Bill,that is an excellent solution. I over thought the process by deleting the deeper most folders first.
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
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
ASKER
Scott the comments (and especially the article) were extremely helpful. I was way overthinking it.
Use method below to see if folder is empty:
Open in new window
Here is example to remove folder:Open in new window