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.


# Get the date for today
$Today = Get-Date

#Configure number of days to keep log files
$Days = “40"
$Daytoinspect = $Today.AddDays(-$Days)

#Configure the path of log files to inspect
$LogFolder = “F:\IIS_Logs”

#Define the log extension
$LogExt = “*.log”

#Get Files
$Old_Files = Get-Childitem $LogFolder -Include $LogExt -Recurse | Where { $_.LastWriteTime -le “$Daytoinspect” }

#Deleting those files
foreach ($File in $Old_Files){
  if ($File -ne $NULL) {
     Write-Host “File found , we are deleting File $File” -ForegroundColor “magenta”
     Remove-Item $File.FullName -Recurse | out-null
  else {
     Write-Host “Script Ends” -foregroundcolor “Green”