Friday 1 August 2008

VBScript to Delete Files Older Than 14 Days

The VBScript can be run from the Windows command line or added to a windows script. It accepts a start directory as a parameter and searches through the directory and subdirectories deleting files older than 14 days.

(You can change the 14 in the code to any number of days)

Save this code in a file called DeleteOldFiles.vbs

Sub processFolder(ByRef folder, ByVal path)
  For Each file In folder.Files
    If DateDiff("d",file.datelastmodified,Date) > 14 Then
      Wscript.Echo "Deleting: "&path&"/"&file.Name
      file.Delete
    End If
  Next
  For Each subfolder In folder.SubFolders
    processFolder subfolder, path&"/"&folder.Name
  Next
End Sub
processFolder CreateObject("Scripting.FileSystemObject").GetFolder(WScript.Arguments(0)), WScript.Arguments(0)

To run the script from the command line issue the following statement, changing c:\temp to your starting directory:

cscript.exe DeleteOldFiles.vbs c:\temp


Or for the current directory

cscript.exe DeleteOldFiles.vbs .


Files Deleted Successfully.

No comments: