Wednesday, January 30, 2013

IIS Log Management Script in Powershell

IIS logs on a busy webserver can use up a lot of disk space. I wrote this little powershell script that I schedule to run on all of my web servers. It goes in and deletes out any IIS logs older than 1 year. Then it compresses any IIS logs that are left which are older than 1 day and are not already compressed. You can change the length of time for these to suit your needs by changeing the numbers in the "AddDays(-123)" parts of the script. Just make sure it's a negative number, or else you won't have any logs left.


########################################################
## IIS Log Management
## Caution: Use at your own risk. 
## No warranty expressed or implied.
## Written by: Greg Kjono on 12/1/2011
########################################################

$version = gwmi win32_operatingsystem | select version
$version = $version.version.substring(0,4)
$ErrorActionPreference = "Continue"

if ($version -ge "6.0."){
 ## If the OS is 2k8 or higher, set this log path
 [STRING]$dir = "c:\inetpub\logs\logfiles\"
}else{
 ## Otherwise set this log path
 [STRING]$dir = $env:windir + "\system32\LogFiles\"
}

if ($dir){
Set-Location $dir

## For all directories that start with "W3SVC" run the following
foreach ($LogDir in Get-ChildItem $dir | Where {$_.PsIsContainer -and $_.Name -match "^W3SVC"}){
 [STRING]$wrkDir =  $dir + $LogDir + "\"
 Set-Location $wrkDir

 ## Delete iis logs older than 1 year
 Get-ChildItem $wrkDir | where {$_.lastWriteTime -lt (Get-Date).AddDays(-365)} | Remove-Item -Force
 
 ## compress IIS logs older than 1 day that aren't already compressed
 Foreach ($log in Get-ChildItem $wrkDir | where {$_.lastWriteTime -lt (Get-Date).AddDays(-1) -and $_.Attributes -notcontains 'Compressed'}){
         $file = $wrkDir + $log.Name
         $tempCmd = "Compact /C " + $file
  Invoke-Expression -command $tempCmd
  }
 }
}