How to Delete Old IIS Logs with Scheduled Task

IIS can rotate log files.  I just wish it could also delete log files older than x number of days.

Since IIS 7.5 does not do it, I would have to write a quick powershell script for it.

To begin, the following will list all files within the folder/subfolders (i.e. the whole tree recursively) that is older than 30 days and match the file name pattern “u_ex*.log”.

   1: $srcPath = "C:\inetpub\logs\LogFiles\"

   2: $filePattern = "u_ex*.log"

   3: $cutoffDays = 30

   4:  

   5: # output the file names to delete

   6: Get-ChildItem $srcPath -Include $filePattern -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(0-$cutoffDays)} | out-string

 

Once you are comfortable, you can replace “out-string” with “Remove-Item”.  It will delete those old files.

   1: $srcPath = "C:\inetpub\logs\LogFiles\"

   2: $filePattern = "u_ex*.log"

   3: $cutoffDays = 30

   4:  

   5: # delete the files

   6: Get-ChildItem $srcPath -Include $filePattern -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(0-$cutoffDays)} | Remove-Item

 

Say you also want to keep a log of the files you are deleting:

   1: $srcPath = "C:\inetpub\logs\LogFiles\"

   2: $filePattern = "u_ex*.log"

   3: $cutoffDays = 30

   4: $logFolder = "C:\temp\"

   5: $logPath = $logFolder + (Get-Date).tostring("yyyyMMdd") + "_cleanuplog.txt"

   6:  

   7: # log file names to delete to a log file

   8: Get-ChildItem $srcPath -Include $filePattern -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(0-$cutoffDays)} | out-file $logPath -Append

   9:  

  10: # delete the files

  11: Get-ChildItem $srcPath -Include $filePattern -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(0-$cutoffDays)} | Remove-Item

 

Special thanks to Nathan Hartley’s powershell answer.

Reference:

http://serverfault.com/questions/315721/how-do-i-setup-iis-to-rotate-logs

http://www.howtogeek.com/204088/how-to-use-a-batch-file-to-make-powershell-scripts-easier-to-run/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s