Link to home
Start Free TrialLog in
Avatar of mark fillmore
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
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Avatar of Bill Prew
Bill Prew

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
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
Avatar of mark fillmore

ASKER

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