Delete Log files older than X days

We all have lot of log files. For Exchange for example, IIS log files on CAS server contain many useful information that you can analyze and get lot of information from it. But they quickly start to occupy a lot of disk space.

I usually schedule a script to clean up log files. Here is a sample script that you can schedule as a schedule task and run it in daily basis to clean your log files older than X days:

# Script Start

#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 | out-null
Write-Host “Script Ends” -foregroundcolor “Green”

# Script END

Download Script

Download the Script from here :

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s