I’ll provide a VB Script that I’m running on a Windows 2008 dedicated server; it will delete all old log files (IIS, FTP and SMTP) automatically after a specified number of days.
Keep all log files is great idea to analytic the usage of a particular service and especially when the service is under attack, you need to know exactly Who attack you/Where attacker comes from (based on their IP address), How often they send the request to your server (based on the timestamp) and Which file/location they send the request to, etc to investigate your issue.
However, if these logs are kept for a long time, your hard drives may be full up and your services may stop working. Therefore, create a schedule to clean up all old log files after a specified number of days automatically is the second idea you need to think about.
VB Script delete log files older than a defined day
This script defines DeleteOldLogFiles() function which will scan a specified log folder and delete all files older than a specified number of days.
Option Explicit
' Delete all IIS Log Files older than 30 days
Call DeleteOldLogFiles("C:/WINDOWS/system32/LogFiles/W3SVC2", 30)
' Delete all FTP Log Files older than 30 days
Call DeleteOldLogFiles("C:/WINDOWS/system32/LogFiles/MSFTPSVC1", 30)
' Delete all SMTP Log Files older than 30 days
Call DeleteOldLogFiles("C:/WINDOWS/system32/LogFiles/SMTPSVC1", 30)
Function DeleteOldLogFiles(strPath2Logs, intDays2Keep)
Dim fso, f, fc, f1, strFiles
strFiles = ""
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strPath2Logs)) Then
Set f = fso.GetFolder(strPath2Logs)
Set fc = f.Files
'-- Determine if file is older than defined days
For Each f1 in fc
If DateDiff("d", f1.DateLastModified, Now) > intDays2Keep Then
strFiles = strFiles & f1.Name & vbCrLf
WScript.Echo "Deleted file: " & f1.Name & " - " & DateDiff("d", f1.DateLastModified, Now)
f1.Delete(True)
End If
Next
Set f1 = Nothing
Set fc = Nothing
Set f = Nothing
End If
Set fso = Nothing
End Function |
To make it cleans up the old logs automatically, we may need to create a Task Scheduler which will run that script every day as below:


