Greatest Scripting Hits
Hit Number 1: A script for deleting folders, even though it may not be empty.
For the next few columns, I'll be offering tips from a new set of “Essentials” scripts I’ve posted on my Web site, ScriptingAnswers.com
that have been common requests.
First up: I’m often asked how to use VBScript to delete a folder full of files and, possibly, full of subfolders. The FileSystemObject will delete a folder, but only if it’s empty (in most cases), so you have to recurse through all the subfolders to empty the whole hierarchy. The trick is to make a subroutine that deletes all files in a folder, and then enumerates through each subfolder and calls itself to delete the subfolders’ files. That’s exactly what this script does:
strStartFolder = "C:\Test"
'start by calling a subroutine to delete this
'folder's files and hit its subfolders
Dim objFSO, objFile, objFolder
Set objFSO = CreateObject("Scripting.FileSystemObject")
'enumerate through the files in the folder
'we've been given, for each file, delete it.
For Each objFile In objFSO.GetFolder(strPath).Files
'now enumerate through the subfolders in the
'folder we've been given. for each subfolder,
'we need to call this same subroutine, which
'is called recursion.
For Each objFolder In _
'now that the folder we've been given is empty,
'we can delete it
The trick to make this or any recursion work is to make a subroutine that can handle one layer of the hierarchy, and then let that subroutine call itself for each child object it finds. This won’t work with deeply-stacked folder trees (I think about 16 is the limit), but it’ll cover most situations.
Don’t forget: So long as you have permission and the remote computer has file sharing enabled, the starting path can be a UNC, making this useful for deleting folders on remote machines, too.
Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is an Author/Evangelist for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.