Age-Based File Deletion in WSH
(Page 1 of 5 )
I can’t count the number of times I’ve see this question asked on the internet. I probably receive two or three requests a day asking me for a script that can automatically delete files that are older than seven days.
So I’ve decided to make an article of it and show you just how easy it is to delete files based on age with WSH. I’m going to help you create a good base script that can be used by its self or expanded into a much larger script.
Since this code is most likely going to be used inside of another script I decided to write it in a modularized fashion. In other words, it’s going to be a series of subroutines that can easily be dropped into any other script.
To begin, we’ll connect to the FileSystemObject and create the subroutine that will perform the actual file deletion. A simple beginning looks like this:
numDays = 7
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFile = objFso.GetFile("C:\test.txt")
Sub DeleteOldFile(objFile, numDays)
dateFile = objFile.DateLastModified
dateToday = Now()
If dateFile <= dateToday Then
daysOld = dateToday - dateFile
If daysOld > numDays Then
objFile.Delete
End If
Else
WScript.Echo "Incorrect date stamp in", strFile
End If
End Sub
That’s exactly what you were thinking, right? Okay, it looks a lot harder than it really is. Here’s what we have going on in our subroutine.
The subroutine only requires two parameters.
The first is file object representing the file that we would like to delete. At this point you should know how to connect to the FileSystemObject and grab a file. If not, the first two lines aren’t too difficult to figure out—you only need to change the file path.
The second parameter is an integer representing the file age in days.
Next we establish two very important dates: the file’s Last Modified date and today’s date. It would be pretty tough to figure out a file’s age without those two pieces of information. The File object’s DateLastModified property and VBScript’s Now() function both return date type variables.
Because date types are special, they can be calculated much the same way you would a number. Adding or subtracting them results in a floating point number of days. So that’s exactly what we do to determine daysOld.
Finally, a simple If statement determines if the file is older than the given number of days (numDays). If it is, we use the File object’s Delete method. If it isn’t, we leave it alone.
I’ve also added a little error handling in there that will flag if a file’s date is newer than today’s date. That would indicate a problem in the file’s date stamp, or a change in the system time since the file was last modified.
Next: Adding some error-handling >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer