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.

1 comment:

  1. I originally wrote this post based on PowerShell 2.0 on Windows Server 2008 R2. Newer versions of PowerShell have a -File parameter for Get-ChildItem. If you use that, you can skip the !$_PSIsContainer part of the Where-Object query.

    ReplyDelete