Skip to content

Create a bat script to clean up the backlog log files

Posted in Education, and WhoCodeFirst

You can use below batch script file to clean up old log files in a Windows environment:

rem Script to clean up log files in a Windows environment 
 @echo off

rem Set the directory where the log files are located
 set log_dir="C:\Logs"

rem Set the age (in days) of the files to be deleted
 set age=30

rem Find and delete log files older than 30 days
 forfiles /p %log_dir% /s /m *.log /d -%age% /c "cmd /c del @path"

rem Print a message to indicate the script has completed
 echo Log file cleanup complete.

This script uses the forfiles command to locate all files with the .log file extension in the specified directory (C:\Logs) that are older than 30 days. The /c “cmd /c del @path” flag is used to execute the del command on those files, which will delete them.

You can modify the script to suit your requirements, for example, if you want to clean up files older than 7 days, just change the age variable to 7.

You can also add some more checks to the script such as checking the disk space before and after the cleanup, or sending an email notification after the script has completed.

Please be careful when using any script that deletes files, as it’s always a good idea to test it on a small set of files before running it on production systems.

Happy Learning!

If you enjoyed this article, Get email updates (It’s Free)
Translate »