Wednesday, January 26, 2011

Recursively Delete Files by Extension Name

Const strExtensionsToDelete = "wav,avi,mp3,aac,tmp,bak"
Const testMode = True

Sub RecursiveDeleteByExtension(ByVal strDirectory, strExtensionsToDelete)
  Dim objFolder, objSubFolder, objFile
  Dim strExt
  Set objFolder = objFSO.GetFolder(strDirectory)
  For Each objFile in objFolder.Files
    For Each strExt in Split(Ucase(strExtensionsToDelete),",")
      If Right(Ucase(objFile.Path), Len(strExt)+1) = "." & strExt Then
        wscript.echo "Deleting:" & objFile.Path
        If Not testMode = True Then
          objFile.Delete
        End If
        'Exit For
      End If
    Next
  Next 
  For Each objSubFolder in objFolder.SubFolders
    RecursiveDeleteByExtension objSubFolder.Path, strExtensionsToDelete
  Next
End Sub

Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
RecursiveDeleteByExtension "d:\downloads", strExtensionsToDelete
wscript.echo "finished!"

1 comment:

  1. I updated this on 2/28/2011 to comment the "Exit For" line in the first routine.

    ReplyDelete