Wednesday 15 January 2014

Windows - Batch file to clean old Log Files

After dealing with several hundred GB of log files from Tomcat, I created a simple cleanup script for old log files. This script is meant to be run by a Schedule Task in Windows so its configuration is very simple. It only needs to know three things: Path to search, Type of Files and the number of days to keep the files.

You can download the batch file here, or copy paste the following text:


echo off
REM ********************************
REM *       USER VARIABLES         *

REM CLEAN FILES OLDER THAN NUM_DAYS
set NUM_DAYS=7

REM PATH WHERE TO RECURSIVELY SEARCH FOR FILES
set SRCDIR=C:\LOGS

REM FILE EXTENSION TO LOOK FOR (*.* FOR ALL FILES)
set EXT="*.log"
REM ********************************


echo "Cleaning Files older than %NUM_DAYS% on %SRCDIR%"

forfiles /p "%SRCDIR%" /s /m %EXT% /D -%NUM_DAYS% /C "cmd /c del @path"

echo "DONE!"
echo on


Super simple! It requires the forfiles command to be installed (it already comes Windows Server 2003 and onwards, Windows Vista and onwards. Windows XP users have to install it manually)

You can used this in conjunction with a schedule task to make the script run automatically at any given day/time. 

You can also modified it to move the files, zip them or event rename them.
I suppose this can also be done with Windows Powershell, but since I'm more into Linux I don't have a clue on how to do it. If you have a similar Powershell script please share it, or let me know where I can download it from! 



No comments:

Post a Comment