Thursday, January 29, 2015

Script to Remove Old IIS Logs

One of the ongoing issues I seem to run into is Exchange servers running low on disk space for the C: drive. When this happens messages stop flowing because Exchange doesn't want to run out of disk space.

Much of the time, the disk space on C: is being eaten up by IIS logs. IIS does not have any functionality to automatically delete old logs. So, I've seen servers with years of logs stored in C:\Inetpub\Logs\.

Here is a script that you can schedule as a task to remove old IIS log files:
# Adjust these two variables
$iisLogDir = "C:\inetpub\logs"
$deleteAfterDays = 14

#calculate date for deletion
$removeDate = (Get-Date).AddDays(-$deleteAfterDays)

#Delete Files
Get-ChildItem -Path $iisLogDir -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $removeDate } | Remove-Item -Force
This calculates the age of the file based on the creation time. If you want it to be based on modified time use $_.LastWriteTime instead.

The Where-Object command uses !$_.PSIsContainer (not container) to skip directories and only select files.

No comments:

Post a Comment