dantpro icon

IIS Log File Cleanup and Archive

dantpro | PRO | 04/08/14 12:54:51 PM UTC | 0 ⭐ | 699 👁️ | Never ⏰ | []
PowerShell |

8.03 KB

|

None

|

0 👍

/

0 👎

<#
.SYNOPSIS
IISLogsCleanup.ps1 - IIS Log File Cleanup Script
 
.DESCRIPTION 
Creates zip archives of IIS log files older than the first day
of the previous month.
 
.PARAMETER Logpath
The IIS log directory to cleanup.
 
.PARAMETER ArchivePath
The path to a location where zip files are moved to, for example
a central log repository stored on a NAS.
 
.EXAMPLE
.\IISLogsCleanup.ps1 -Logpath "D:\IIS Logs\W3SVC1"
 
.EXAMPLE
.\IISLogsCleanup.ps1 -Logpath "D:\IIS Logs\W3SVC1" -ArchivePath "\\nas01\archives\iislogs"
 
.LINK
http://exchangeserverpro.com/powershell-script-iis-logs-cleanup
 
.NOTES
Written By: Paul Cunningham
Website:    http://exchangeserverpro.com
Twitter:    http://twitter.com/exchservpro
 
Additional Credits:
Filip Kasaj - http://ficility.net/2013/02/25/ps-2-0-remove-and-compress-iis-logs-automatically/
 
Change Log
V1.00, 7/04/2014, Initial version
#>
 
 
[CmdletBinding()]
param (
    [Parameter( Mandatory=$true)]
    [string]$Logpath,
 
    [Parameter( Mandatory=$false)]
    [string]$ArchivePath
    )
 
 
#-------------------------------------------------
#  Variables
#-------------------------------------------------
 
$sleepinterval = 10
 
$computername = $env:computername
 
$date = Get-Date
$currentmonth = ($date.ToString("MM/yy"))
$previousmonth = ($date.AddMonths(-1).ToString("MM/yy"))
[string]$firstdayofpreviousmonth = Get-Date "01/$previousmonth"
 
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$output = "$myDir\IISLogsCleanup.log"
 
 
#...................................
# Logfile Strings
#...................................
 
$logstring0 = "====================================="
$logstring1 = " IIS Log File Cleanup Script"
 
 
#-------------------------------------------------
#  Functions
#-------------------------------------------------
 
#This function is used to write the log file for the script
Function Write-Logfile()
{
    param( $logentry )
    $timestamp = Get-Date -DisplayHint Time
    "$timestamp $logentry" | Out-File $output -Append
}
 
 
#-------------------------------------------------
#  Script
#-------------------------------------------------
 
#Log file is overwritten each time the script is run to avoid
#very large log files from growing over time
 
$timestamp = Get-Date -DisplayHint Time
"$timestamp $logstring0" | Out-File $output
Write-Logfile $logstring1
Write-Logfile "  $date"
Write-Logfile $logstring0
 
 
#Check whether IIS Logs path exists, exit if it does not
if ((Test-Path $Logpath) -ne $true)
{
    $tmpstring = "Log path $logpath not found"
    Write-Warning $tmpstring
    Write-Logfile $tmpstring
    EXIT
}
 
 
$tmpstring = "Current Month: $currentmonth"
Write-Host $tmpstring
Write-Logfile $tmpstring
 
$tmpstring = "Previous Month: $previousmonth"
Write-Host $tmpstring
Write-Logfile $tmpstring
 
$tmpstring = "First Day of Previous Month: $firstdayofpreviousmonth"
Write-Host $tmpstring
Write-Logfile $tmpstring
 
#Fetch list of log files older than 1st day of previous month
$logstoremove = Get-ChildItem -Path "$($Logpath)\*.*" -Include *.log | Where {$_.LastWriteTime -lt $firstdayofpreviousmonth -and $_.PSIsContainer -eq $false}
 
if ($($logstoremove.Count) -eq $null)
{
    $logcount = 0
}
else
{
    $logcount = $($logstoremove.Count)
}
 
$tmpstring = "Found $logcount logs earlier than $firstdayofpreviousmonth"
Write-Host $tmpstring
Write-Logfile $tmpstring
 
#Init a hashtable to store list of log files
$hashtable = @{}
 
#Add each logfile to hashtable
foreach ($logfile in $logstoremove)
{
    $zipdate = $logfile.LastWriteTime.ToString("yyyy-MM")
    $hashtable.Add($($logfile.FullName),"$zipdate")
}
 
#Calculate unique yyyy-MM dates from logfiles in hashtable
$hashtable = $hashtable.GetEnumerator() | Sort Value
$dates = @($hashtable | Group -Property:Value | Select Name)
 
#For each yyyy-MM date add those logfiles to a zip file
foreach ($date in $dates)
{
    $zipfilename = "$Logpath\$computername-$($date.Name).zip"
 
    if(-not (test-path($zipfilename)))
    {
        set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
        (dir $zipfilename).IsReadOnly = $false 
    }
 
    $shellApplication = new-object -com shell.application
    $zipPackage = $shellApplication.NameSpace($zipfilename)
 
    $zipfiles = $hashtable | Where {$_.Value -eq "$($date.Name)"}
 
    $tmpstring = "Zip file name is $zipfilename and will contain $($zipfiles.Count) files"
    Write-Host $tmpstring
    Write-Logfile $tmpstring
 
    foreach($file in $zipfiles) 
    { 
        $fn = $file.key.ToString()
        
        $tmpstring = "Adding $fn to $zipfilename"
        Write-Host $tmpstring
        Write-Logfile $tmpstring
 
        $zipPackage.CopyHere($fn,16)
 
        #This sleep interval helps avoids file lock/conflict issues. May need to increase if larger
        #log files are taking longer to add to the zip file.
        Start-sleep -s $sleepinterval
    }
 
    #Compare count of log files on disk to count of log files in zip file
    $zippedcount = ($zipPackage.Items()).Count
    
    $tmpstring = "Zipped count: $zippedcount"
    Write-Host $tmpstring
    Write-Logfile $tmpstring
    
    $tmpstring = "Files: $($zipfiles.Count)"
    Write-Host $tmpstring
    Write-Logfile $tmpstring
 
    #If counts match it is safe to delete the log files from disk
    if ($zippedcount -eq $($zipfiles.Count))
    {
        $tmpstring = "Zipped file count matches log file count, safe to delete log files"
        Write-Host $tmpstring
        Write-Logfile $tmpstring
        foreach($file in $zipfiles) 
        { 
            $fn = $file.key.ToString()
            Remove-Item $fn
        }
 
        #If archive path was specified move zip file to archive path
        if ($ArchivePath)
        {
            #Check whether archive path is accessible
            if ((Test-Path $ArchivePath) -ne $true)
            {
                $tmpstring = "Log path $archivepath not found or inaccessible"
                Write-Warning $tmpstring
                Write-Logfile $tmpstring
            }
            else
            {
                #Check if subfolder of archive path exists
                if ((Test-Path $ArchivePath\$computername) -ne $true)
                {
                    try 
                    {
                        #Create subfolder based on server name
                        New-Item -Path $ArchivePath\$computername -ItemType Directory -ErrorAction STOP
                    }
                    catch
                    {
                        #Subfolder creation failed
                        $tmpstring = "Unable to create $computername subfolder in $archivepath"
                        Write-Host $tmpstring
                        Write-Logfile $tmpstring
 
                        $tmpstring = $_.Exception.Message
                        Write-Warning $tmpstring
                        Write-Logfile $tmpstring
                    }
                }
 
                try 
                {
                    #Move the zip file
                    Move-Item $zipfilename -Destination $ArchivePath\$computername -ErrorAction STOP
                    $tmpstring = "$zipfilename was moved to $archivepath\$computername"
                    Write-Host $tmpstring
                    Write-Logfile $tmpstring
                }
                catch
                {
                    #Move failed, log the error
                    $tmpstring = "Unable to move $zipfilename to $ArchivePath\$computername"
                    Write-Host $tmpstring
                    Write-Logfile $tmpstring
                    Write-Warning $_.Exception.Message
                    Write-Logfile $_.Exception.Message
                }   
            }
        }
 
    }
    else
    {
        $tmpstring = "Zipped file count does not match log file count, not safe to delete log files"
        Write-Host $tmpstring
        Write-Logfile $tmpstring
    }
 
}
 
 
#Finished
$tmpstring = "Finished"
Write-Host $tmpstring
Write-Logfile $tmpstring

Comments