The other day I started scouring the web for a VBScript to use for deleting files that had not been modified for a certain number of days. I tried several, some of which were designed to delete files in a given folder, some that deleted certain file extensions recursively, but none that did it recursively by age alone.
When I say “age” I mean the DateLateModified property of the file object in question. In this script, you specify the number of days (most accurate method), and the target folder, and the name of a logfile.txt that you want generated, as well. With the log file you can look for OK on success and Failed if the delete didn’t work.
I put my scripts in a folder at C:scripts. I called this one delete.vbs.
To run this script, copy the code to your favorite text editor, save the file as a .vbs, open a command line to the directory and type “cscript delete.vbs”
Remember to edit:
1. Line 1 which indicates the target folder where files are going to be deleted
2. Line 2 which indicates the logfile that will be created
3. Line 3 which indicates how many days old you’re starting with… files with a DateLastModified OLDER than this date will be deleted permanently.
You should be able to access the logfile after the script runs.
Here’s the code:
- strFolder = "C:\Test"
- logfilename = "C:\scripts\testlog.txt"
- intDays = 1277
- ForAppending = 8
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- Set objFolders = objFSO.GetFolder(strFolder)
- objToday = Now()
- objPastDate = DateAdd("d", intDays*-1, objToday)
- Set objOutFile = objFSO.OpenTextFile(logfilename,ForAppending, True)
- objOutFile.WriteLine "——————————"
- objOutFile.WriteLine "Run at " & Date()
- objOutFile.WriteLine "——————————"
- Recurse objFolders
- Sub recurse(ByRef objFolders)
- Set objSubFolders = objFolders.SubFolders
- Set objFiles = objFolders.Files
- For Each File In objFiles
- If File.DateLastModified < objPastDate Then
- On Error Resume Next
- objOutFile.Write "Deleting " & File.Path & "\" & File.Name
- File.Delete
- If Err.Number = 0 then
- objOutFile.WriteLine "..OK"
- else
- objOutFile.WriteLine "..Failed"
- end if
- On Error Goto 0
- End If
- Next
- For Each Folder In objSubFolders
- recurse Folder
- If Folder.DateLastModified < objPastDate Then
- On Error Resume Next
- objOutFile.Write "Deleting " & Folder.Path & "\" & Folder.Name
- objFSO.DeleteFolder Folder.Path, True
- If Err.Number = 0 then
- objOutFile.WriteLine "..OK"
- else
- objOutFile.WriteLine "..Failed"
- end if
- On Error Goto 0
- Else
- End If
- Next
- Set objSubFolders = Nothing
- Set objFiles = Nothing
- End Sub