Delete files older than 7 days

Here is a small visual basic script that will delete all files in a folder older than 7 days with a specific file extension. I use it to clean out old spam that’s been archived on our exchange 2003 mail server by the IMF (intelligent message filter). I use task scheduler on the server to run the task once a day.

I have added a few options that are commented out. In vb script this is done with a apostrophe ‘  so just remove to make it active.

1. number of days (7 in this example)

dtmDate = Date - 7

2. by creation date

strDate = Left(objFile.CreationDate, 8)

3. by last modified date

strDate = Left(objFile.LastModified, 8)

4.  by file extension (txt in this example)

If objFile.Extension = "txt" Then

Here is the vb script

'Change the number of days to suite your needs
dtmDate = Date - 7

strDay = Day(dtmDate)

If Len(strDay) < 2 Then
 strDay = "0" & strDay
End If

strMonth = Month(dtmDate)

If Len(strMonth) < 2 Then
 strMonth = "0" & strMonth
End If

strYear = Year(dtmDate)

strTargetDate = strYear & strMonth & strDay

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set FileList = objWMIService.ExecQuery _
 ("ASSOCIATORS OF {Win32_Directory.Name='C:\Progra~1\Exchsrvr\Mailroot\vsi1~1\UceArchive\ToDelete'} Where " _
 & "ResultClass = CIM_DataFile")

For Each objFile In FileList
 'by creation date
 'strDate = Left(objFile.CreationDate, 8)
 'by modified date
 strDate = Left(objFile.LastModified, 8)
 If strDate < strTargetDate Then
 'uncomment this line below and extra the "End if" to match by file extension
 'If objFile.Extension = "txt" Then
 objFile.Delete
 End If
 'End If
Next

Credits mostly to Hey, Scripting Guy! he is a legend

http://blogs.technet.com/b/heyscriptingguy/archive/2007/11/13/hey-scripting-guy-how-can-i-remove-old-files-from-all-the-folders-that-share-a-folder-name.aspx