Peter Hinchley

Recursively Delete Files Using VBScript

Tagged: windows, vbscript

The following VBScript can be used to recursively delete files on a Microsoft Windows system. The script leverages the Windows Scripting object FileSystemObject.

The script can be customized by modifying two constants. The first, START_FOLDER, is used to set the starting point for the recursion. The second, PREFIX, is used to determine the files that are to be deleted. In particular, a file will be deleted if it begins with the character string defined by PREFIX.

The code is specifically configured to delete files named .DS_Store, which are the hidden files created by Apple OS X to store folder customization data. These files are created on my Windows 7 system whenever I connect to the file system remotely from my Apple MacBook Pro. I use the script periodically to remove the files from Windows.

To use the script, save the code into a file named C:\Temp\deletefiles.vbs. Open a command prompt, navigate to C:\Temp, and enter the following command:

cscript.exe deletefiles.vbs

The script will output the total number of deleted files.

START_FOLDER = "C:\Temp"
PREFIX = ".DS_Store"

Set oFSO = CreateObject("Scripting.FileSystemObject")

ProcessSubFolders oFSO.GetFolder(START_FOLDER), iCount

Sub ProcessSubFolders(oFolder, iCount)
  Set cFiles = oFolder.Files
  For Each oFile In cFiles
    If Left(oFile.Name, Len(PREFIX)) = PREFIX Then
      oFile.Delete
      iCount = iCount + 1
    End If
  Next
  For Each oSubFolder In oFolder.SubFolders
    ProcessSubFolders oSubFolder, iCount
  Next
End Sub

WScript.Echo "Files deleted: " & iCount

Your Say