Powershell Script To Clear Old IIS Logs

If you have many sites running on your installation of Windows Server, you will soon find that there will be an accumulation of logs generated by IIS. Through my niavity, I presumed that there is a default setting in IIS that would only retain logs for a specific period of time. It is only when I started noticing over the last few weeks the hard disk space was slowly getting smaller and smaller.

Due to my sheer embaressment, I won't divulge how much space the logs had taken up. All I can say, it was quite a substantial amount. :-)

After some Googling online, I came across a Powershell script (which can be found here), that solved all my problems. The script targets your IIS logs folder and recusively looks for any file that contains ".log" for deletion. Unfortunately, the script did not run without making some minor modifications to the original source. This is due to changes in versions of Powershell since the post was written 3 years ago.

$logPath = "C:\inetpub\logs\LogFiles" 
$maxDaystoKeep = -5
$cleanupRecordPath = "C:\Log_Cleanup.log" 

$itemsToDelete = dir $logPath -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($maxDaystoKeep)) 

If ($itemsToDelete.Count -gt 0)
{ 
    ForEach ($item in $itemsToDelete)
    { 
        "$($item.FullName) is older than $((get-date).AddDays($maxDaystoKeep)) and will be deleted." | Add-Content $cleanupRecordPath 
        Remove-Item $item.FullName -Verbose 
    } 
} 
Else
{ 
    "No items to be deleted today $($(Get-Date).DateTime)." | Add-Content $cleanupRecordPath 
}    

Write-Output "Cleanup of log files older than $((get-date).AddDays($maxDaystoKeep)) completed!" 

Start-Sleep -Seconds 10

If you're ever so inclined, hook this script up to a Scheduled Task to run on a daily basis to keep your log files in order.

blog comments powered by Disqus