VBScript to Delete Files in a Directory Older Than X Days - Something Wicked This Way Comes

Something Wicked This Way Comes

Jan 9 2009   3:59PM GMT

VBScript to Delete Files in a Directory Older Than X Days



Posted by: Spencer Kuziw

I recently needed to whip up a quick script to delete all files in a directory that were older than X number of days. Hopefully it is something that you can use, too. Copy the code and paste it into a text file named something like “cleanup-folder.vbs” and set the variables for strDir (the absolute path to the directory) and strDays (files older than this number of days will be deleted).

CODE:
  1. ‘ ################################################################
  2. # cleanup-folder.vbs
  3. ‘ #
  4. # Removes all files older than 1 week
  5. ‘ # Authored by Spencer Kuziw (s.kuziw-at-epic.ca)
  6. # Based on code by YellowShoe
  7. ‘ # Version 1.0 - Sept 23 2008
  8. ################################################################
  9.  
  10. Dim fso, f, f1, fc, strComments, strScanDir
  11.  
  12. ‘ user variables
  13. —————————————————————-
  14.  
  15. strDir = “FULL\PATH\TO\FOLDER\TO\BE\CLEANED”
  16. strDays = 7
  17.  
  18. ‘ DO NOT EDIT BELOW THIS LINE
  19. (unless you know what you are doing)
  20. ‘——————————————————————
  21. Set fso = CreateObject("Scripting.FileSystemObject")
  22. Set f = fso.GetFolder(strDir)
  23. Set fc = f.Files
  24. For Each f1 in fc
  25.       If DateDiff("d", f1.DateCreated, Date)> strDays Then
  26.             ‘strComments = strComments & f1.name & ” “ & f1.DateCreated & vbCrLf
  27.             fso.DeleteFile(f1)
  28.       End If
  29. Next
  30.  
  31. ‘wscript.echo strComments
  32. WScript.Quit
  33. eof

Comment on this Post


You must be logged-in to post a comment. Log-in/Register