Auto delete old log files after retention period (VBScript)

Do you have a problem that old log files fill up your harddisk?  If you have hundred of servers, it takes a lot of time to manually delete useless log files on each server.

The below vbscript file can auto delete old files in folders which exceed our per-defined retention period.

Just save the below stuff as a .vbs files and add a daily/weekly/monthly schedule job inside Windows.

' tmp_log_Cleanup.vbs
' Auto delete old files (e.g. log, badmail, etc) after retention period

Option Explicit

Dim fso, dTwoWeeksAgo

Set fso = CreateObject("Scripting.FileSystemObject")

'Syntax:  DirWalk("F:\users\data\", 180)   ' Retaining period (days)
DirWalk "D:\inetpub\mailroot\BadMail\", 180 
DirWalk "D:\inetpub\mailroot\Drop\", 180 
DirWalk "D:\Spam Mail Storage\Custome Black List\", 60 

' Log File
DirWalk "C:\WINNT\system32\LogFiles\W3SVC1\", 400

DirWalk "D:\SMTP Log\SMTPSVC1\", 400
DirWalk "C:\Documents and Settings\user\Local Settings\Temp\", 90
DirWalk "C:\Documents and Settings\user\Local Settings\Temporary Internet Files\", 90

DirWalk "C:\WINNT\Temp\", 90

Sub DirWalk(parmPath, parmDays)
Dim oSubDir, oSubFolder, oFile, n

   On Error Resume Next         ' We'll handle any errors ourself, thank you very much

   Set oSubFolder = fso.getfolder(parmPath)

   For Each oFile In oSubFolder.Files   ' look in the current dir
      If Err.Number <> 0 Then   ' if we got an error, just skip this entry
      ElseIf oFile.DateLastModified < Date() - parmDays Then
        '' Wscript.Echo "about to delete " & oFile.Path
      '''uncomment the next line when you are satisfied this script works properly
         ' fso.DeleteFile oFile.Path, True – this is slow
         oFile.Delete   ' using direct object delete command is much faster – updated on 2013-06-03
      End If

   For Each oSubDir In oSubFolder.Subfolders
      DirWalk oSubDir.Path, parmDays      ' recurse the DirWalk sub with the subdir paths

   On Error Goto 0   ' Resume letting system handle errors.

End Sub


Popular Posts