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:
If you execute the following lines of code:
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.
Dim theFso, theFolder
set theFso = CreateObject("Scripting.FileSystemObject")
If thefso.folderExists(folderPath)=False Then
Wscript.echo "Folder ‘" & folderPath & "’ does not exist."
Set theFolder = thefso.getfolder(folderPath)
If thefolder.files.count > 0 Then
Wscript.echo "Folder contains " & theFolder.files.count & " file(s)."
Wscript.echo "Folder contains no files."
If theFolder.subfolders.count > 0 Then
Wscript.echo "Folder contains " & theFolder.subfolders.count & _
Wscript.echo "Folder contains no subfolders."
Set theFolder = Nothing
Wscript.echo "Deleting: " & folderPath