Monday, August 09, 2004

VBScript to delete files by date

Here's a little ditty to look for files of a particular age in a particular folder and delete them. Saved me a headache today.

I find VBScript much like college Spanish class. It's really easy to understand, but really hard to remember for very long.

'--------------------------------------------
'
' Script to Delete Files
' in a particular folder
' over seven days old
'
'--------------------------------------------

'create object and define folder to search
Set fso = CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder("C:\test")

'rem the next line to run silently
msgbox "It is now: " & now

'loop through files
For Each file In fol.Files

'get the difference in dates
'other options are yyyy, q, m, y, w, ww, h, n, s
myDiff = datediff("d",file.datecreated,now)

'lets say 7 days old
if myDiff > 7 then
'rem the next line to run silent
msgbox "Deleting: " & file.Name & " " & file.datecreated & " " & myDiff
'delete the file here where 'the 1 (TRUE) forces deletion of readonly files
file.delete 1
'rem the next two lines to run silently
else
msgbox "Not deleting: " & file.Name & " " & file.datecreated & " " & myDiff
end if
Next

'end of script
'--------------------------------------------

1 comment:

  1. Anonymous4:59 PM

    Works perfect. Nice and simple. Thanks.

    ReplyDelete