It is unfortunately common that software installers will leave behind an empty folder when they are finished. If you want to keep your system clean, you’ll need to add code to your deployment script to remove a folder from the PC if the folder is empty.
The following subroutine will, when passed the path to a folder (e.g., “C:\Test1\Test2”) will delete that folder (in the example, “Test2” but not “Test1”) if that folder is empty (i.e., contains no other files or folders).
For example, let’s say you have the following files and folders on a PC:
- D:\Temp\Test\
- D:\Temp\Test2\
- D:\Temp\Test2\myfile.txt
- D:\Temp\Test3\subfolder\
If you execute the following lines of code:
DeleteFolderIfEmpty(“D:\Temp\Test”)
DeleteFolderIfEmpty(“D:\Temp\Test2”)
DeleteFolderIfEmpty(“D:\Temp\Test3”)
The following things will happen:
- Since there are no files under the D:\Temp\Test directory, the Test directory will be deleted.
- Since there is a file (myfile.txt) under D:\Temp\Test2, that directory will not be deleted.
- Since there is a subfolder under D:\Temp\Test3, that directory will not be deleted.
Feel free to use this code as you see fit.
Sub DeleteFolderIfEmpty(folderPath)
Dim theFso, theFolder
set theFso = CreateObject("Scripting.FileSystemObject")
If thefso.folderExists(folderPath)=False Then
Wscript.echo "Folder ‘" & folderPath & "’ does not exist."
Exit Sub
End If
Set theFolder = thefso.getfolder(folderPath)
If thefolder.files.count > 0 Then
Wscript.echo "Folder contains " & theFolder.files.count & " file(s)."
Exit Sub
Else
Wscript.echo "Folder contains no files."
End If
If theFolder.subfolders.count > 0 Then
Wscript.echo "Folder contains " & theFolder.subfolders.count & _
" subfolder(s)."
Exit Sub
Else
Wscript.echo "Folder contains no subfolders."
End if
Set theFolder = Nothing
Wscript.echo "Deleting: " & folderPath
thefso.DeleteFolder folderPath,True
End Sub