Automatically Delete old IIS logs w/ PowerShell

I’ve seen one too many servers hobbled by a run-away IIS installation. By default, if IIS is enabled and allowed to store its log files, it’s only a matter of time before it consumes every scrap of space on the C:\, leaving no room even for a user profile to be created! When this happens, no one can log onto the machine who hasn’t already stored their profile before. It’s sad. It’s so sad, it even has a frowny face on Server 2012 systems.


Never again will IIS be allowed to tyrannically absorb all file system space! I wrote this script for a client to remove IIS files older than 30 days. Update the $LogPath to point it at your IIS log’s directory, change the $maxDaystoKeep value and the $outputPath value to tell the script where to put your logs. If files exist that are older than 30 days, they’ll be tossed, and a nice log entry created. If not, an entry will be added to the log stating ‘no files to delete today’ instead.

$LogPath = "C:\inetpub\logs"
$maxDaystoKeep = -30
$outputPath = "c:\CleanupTask\Cleanup_Old_logs.log"

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

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

Write-Output "Cleanup of log files older than $((get-date).AddDays($maxDaystoKeep)) completed..."
start-sleep -Seconds 10

I deployed this as a Scheduled Task and it’s running wonderfully thus far. Enjoy!

2 thoughts on “Automatically Delete old IIS logs w/ PowerShell

  1. Michael Hincapie February 17, 2015 / 6:00 pm

    Wow Awesome – Something that i was looking for! and Congratz Stephen for the MVP Award – you truly deserve it.


  2. Sassan Karai January 23, 2017 / 4:37 am

    I find it helpful to use $item.FullName instead of BaseName in case you’re dealing with several webservers on the same machine, this way the output indicates which directory the files were removed from.


Have a code issue? Share your code by going to and pasting your code there, then post the link here!

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.