Thursday, July 6, 2017

Delete and Compress old Log Files using DOS Batch file.

On all of our Exchange Client Access servers, I've been running my Compress and Delete script. Unfortunately, randomly the scheduled task will fail to run the script and the log files don't get purged. This requires kicking off the process by hand to avoid server meltdown.

I am thinking, that powershell may be partially at fault on some of these boxes. Permissions, or run time exceptions, may be causing the script to fail at running. So I've managed to put together this DOS Batch script that does basically the same thing.

  • Deletes all log (and zip) files in the folder older than 30 days
  • (if finds 7-zip) It will compress all log files older than 7 days, then delete them
The one disadvantage that I see is date-stamping. In Powershell, I was going through and stamping the original log files 'last modified' date on the ZIP. This allowed me to easily trigger 30-day deletes on any file in the folder because it would maintain it's original date. I figure that if I run this scheduled task daily, it will only offset the date by 7 days (i.e. an 8 day old log file will take today's date).

I am saving the following as "DOSPurgeOldLogFiles.CMD" and running it from a daily scheduled task.

@Echo off
REM Folder for Log Files
Set InetLogsFolder=c:\inetpub\logs\LogFiles\W3SVC1
if NOT EXIST %InetLogsFolder% Goto :NoLogs

REM Purge all files in log folders older than 30 days old
forfiles -p %InetLogsFolder% /s /m *.* /d -30 /c "cmd /c del @path"

if NOT EXIST "c:\program files\7-Zip\7z.exe" Goto :NoZIP
REM ZIP all files older than 7 days old
for /F %%G in ('forfiles -p %InetLogsFolder% /s /m *.LOG /d -7') DO "c:\program files\7-Zip\7z.exe" a -tzip -mtc=on "%InetLogsFolder%\" "%InetLogsFolder%\%%~G"

REM delete all files that are now ZIP'd
forfiles -p %INETLogsFolder% /s /m *.log /d -7 /c "cmd /c del @path"


Echo Cannot locate log files at %InetLogsFolder%
Echo Install 7-ZIP to compress log files.


No comments:

Post a Comment