Managing IIS logs using programmatically using PowerShell script

Managing IIS logs using programmatically using PowerShell script

Managing IIS logs is a vital task for any administrator which can be automated using a PowerShell script. Logs can quickly build up on high traffic sites which in turn can quickly fill up drives causing other potential issues.

The below script can be used to purge script to a defined time range. In the case of the example 30 days of logs are kept but this can easily be changed by updating the $maxDaystoKeep variable. The all you need to do is a Windows Scheduled task to execute daily.

Import-Module WebAdministration

    $maxDaystoKeep = -30 # number of days to keep IIS logs
    $outputPath = "D:\Netops\" 
    $outputFile = "IIS_log_cleanup.log"
    $logname = $outputPath + $outputFile
    $lognameback = $outputPath + $outputFile + '.bak' + (get-date).ToString(‘hhmmssMMddyyyy’)
    $logpurgesize = '10mb' # set the log file size to purge at
    $logfilepurgedays = '14' # set the number of days to keep log files
    $purgelimit = (Get-Date).AddDays(-$logfilepurgedays)

if(!(Test-Path $outputPath)){New-Item -ItemType Directory -Path $outputPath}

if(Test-Path $logname){$logsize = (get-item $logname).LastWriteTime}

# Manage existing logs
    if(Test-Path $logname){

    $logsize = (get-item $logname).length/$logpurgesize
    Write-Output "$(Get-date) log size is $logsize " | Out-file $logname -append

            if ((get-item $logname).length -gt $logpurgesize){
            
            Write-Output "$(Get-date) $logname is greater than 20MB, rolling over" | Out-file $logname -append
            Write-Output "$(Get-date) rename $logname -to $lognameback" | Out-file $logname -append
            rename-item -path $logname -newname $lognameback
            
            }

     Write-Output "$(Get-date) deleting logs files older than $logfilepurgedays days" | Out-file $logname -append
     Get-Item -Path $outputPath\$outputFile* -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $purgelimit } | Remove-Item -Force 

    }


#starting log
Write-Output "$(Get-date) Starting logging" | Out-file $logname -append


$checkIISinstalled = Get-WindowsFeature -Name Web-Server

if($checkIISinstalled.Installed -eq $True )
{
Write-output "$(Get-date)  IIS is insalled, proceeding" | Add-Content $logname 

    foreach($WebSite in $(get-website))
    {
    $logFile="$($Website.logFile.directory)\w3svc$($website.id)".replace("%SystemDrive%",$env:SystemDrive)
    Write-output "$(Get-date)  Site and directory to purge - $($WebSite.name) [$logfile]" | Add-Content $logname 
    
  
    $itemsToDelete = dir $logFile -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($maxDaystoKeep)) 
    Write-output "$(Get-date) Items to delete $itemsToDelete " | Add-Content $logname 
        if ($itemsToDelete.Count -gt 0)
        { 
            ForEach ($item in $itemsToDelete)
            { 
            # "$($item.BaseName) is older than $((get-date).AddDays($maxDaystoKeep)) and will be deleted" | Add-Content $logname 
            $FileAndPath = $logfile + '\' + $item
            Write-output "$(Get-date) Deleting $FileAndPath" | Add-Content $logname 
            
            # write-host $FileAndPath
            Get-Item $FileAndPath | Remove-Item -Verbose 
            } 
        } 
        else
        { 
        Write-output "$(Get-date) No items to be delete today"  | Add-Content $logname 
        } 
        
    Write-output "$(Get-date) Sleep"  | Add-Content $logname 
    start-sleep -Seconds 5
   
    
    }
}
else
{
Write-output "$(Get-date)  IIS is not insalled, nothing to do !" | Add-Content $logname 

}

Leave a Reply

Your email address will not be published. Required fields are marked *