Monday, August 17, 2009

Log File Cleanup

I needed a tool to clean up log files that exceed a certain age and I remembered a simple executable that I used to have called deleteifolderthan.exe that did just what was required, but when I went looking for it, I couldn't locate it anywhere.

Giving up on that, I decided to write my own script. I needed something that would delete log files over a month old in subdirectories of a parent directory. This is what I came up with:

Const ParentFolder = "E:\Logs"
Const MaxDays = 31
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(ParentFolder)
Set colSubFolders = objFolder.SubFolders
For Each objDir in colSubFolders
Set colFiles = objDir.Files
For Each objFile in colFiles
If DateDiff("d",objFile.DateCreated,now) >= MaxDays Then
objFSO.DeleteFile(objFile.Path)
End If
Next
Next


If you wanted to delete old logs in a single folder, you could simplify this to:

Const WatchFolder = "E:\Logs"
Const MaxDays = 31
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDir = objFSO.GetFolder(WatchFolder)
Set colFiles = objDir.Files
For Each objFile in colFiles
If DateDiff("d",objFile.DateCreated,now) >= MaxDays Then
objFSO.DeleteFile(objFile.Path)
End If
Next


Cheers,
Sean

No comments:

Post a Comment