Delete log files older than X days

In this blog post, I will be showing you how to write a simple script to delete log files older than X days. We will be using PowerShell scripting language to do so. PowerShell is Microsoft scripting language and it is available out of the box on all Windows installations, or at least since Vista.

If you have a noisy system that generates lots of logs, and you want to delete log files older than X days, then you can simply write a script to inspect the logs, and do the cleanup for you. You can then schedule the script to run daily using the Windows task scheduler. It is so easy to delete log files if they are not open or in use, at the time of deletion.

One good example on why to delete log files that are old, is simply IIS log files. IIS log file on busy systems can grow very big, and can even fill your disk space so quickly and might bring the server down, if they are hosted on the system drive.

Even if you have a monitoring system like Microsoft Operations Manager to keep an eye on your disk space, it is always a good idea to periodically delete old log files using a simple criteria.

I usually find the best way to delete log files is by looking at the write time and then compare it to the number of days. The below piece of code will delete any logs with extension “*.log” that are located under F:\IIS_Logs, and older than 40 days.