Delete IIS Logs older than X days

Using Powershell to delete IIS logs older than X days.

I came across a real world requirement to have to use power shell to stop my MS server from clogging up with old IIS logs. It’s pretty bad that MS doesn’t include a simple log rotation method somewhere in the logging handling.

Assuming you’ve installed PowerShell if you need to (it comes with Windows Server 2008 R2) then the first thing to do is open up a PowerShell and alter the execution policy to permit you to run scripts: set-executionpolicy remotesigned

Next create the script itself in Notepad:

get-childitem -Path C:\inetpub\logs\LogFiles -recurse |

where-object {$_.lastwritetime -lt (get-date).addDays(-60)} |

Foreach-Object { del $_.FullName }

The starts at the default logs folder and recursively checks all files down the tree to see if they’re over 60 days since their last write time. If they are then a simple del command removes them.

Save your script as logrotate.ps1

You can then run it from PowerShell by typing from the same directory .\logrotate.ps1

Next you’ll want to make this a scheduled task. The way to execute your new script is to create an entry like this:

powershell.exe c:\scripts\logrotate.ps1  -noprofile -Noninteractive

Set it to a weekly task .

Be the first to comment

Leave a Reply