Advertisement
dantpro

IIS Log File Cleanup and Archive

Apr 8th, 2014
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3. IISLogsCleanup.ps1 - IIS Log File Cleanup Script
  4.  
  5. .DESCRIPTION
  6. Creates zip archives of IIS log files older than the first day
  7. of the previous month.
  8.  
  9. .PARAMETER Logpath
  10. The IIS log directory to cleanup.
  11.  
  12. .PARAMETER ArchivePath
  13. The path to a location where zip files are moved to, for example
  14. a central log repository stored on a NAS.
  15.  
  16. .EXAMPLE
  17. .\IISLogsCleanup.ps1 -Logpath "D:\IIS Logs\W3SVC1"
  18.  
  19. .EXAMPLE
  20. .\IISLogsCleanup.ps1 -Logpath "D:\IIS Logs\W3SVC1" -ArchivePath "\\nas01\archives\iislogs"
  21.  
  22. .LINK
  23. http://exchangeserverpro.com/powershell-script-iis-logs-cleanup
  24.  
  25. .NOTES
  26. Written By: Paul Cunningham
  27. Website:    http://exchangeserverpro.com
  28. Twitter:    http://twitter.com/exchservpro
  29.  
  30. Additional Credits:
  31. Filip Kasaj - http://ficility.net/2013/02/25/ps-2-0-remove-and-compress-iis-logs-automatically/
  32.  
  33. Change Log
  34. V1.00, 7/04/2014, Initial version
  35. #>
  36.  
  37.  
  38. [CmdletBinding()]
  39. param (
  40.     [Parameter( Mandatory=$true)]
  41.     [string]$Logpath,
  42.  
  43.     [Parameter( Mandatory=$false)]
  44.     [string]$ArchivePath
  45.     )
  46.  
  47.  
  48. #-------------------------------------------------
  49. #  Variables
  50. #-------------------------------------------------
  51.  
  52. $sleepinterval = 10
  53.  
  54. $computername = $env:computername
  55.  
  56. $date = Get-Date
  57. $currentmonth = ($date.ToString("MM/yy"))
  58. $previousmonth = ($date.AddMonths(-1).ToString("MM/yy"))
  59. [string]$firstdayofpreviousmonth = Get-Date "01/$previousmonth"
  60.  
  61. $myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
  62. $output = "$myDir\IISLogsCleanup.log"
  63.  
  64.  
  65. #...................................
  66. # Logfile Strings
  67. #...................................
  68.  
  69. $logstring0 = "====================================="
  70. $logstring1 = " IIS Log File Cleanup Script"
  71.  
  72.  
  73. #-------------------------------------------------
  74. #  Functions
  75. #-------------------------------------------------
  76.  
  77. #This function is used to write the log file for the script
  78. Function Write-Logfile()
  79. {
  80.     param( $logentry )
  81.     $timestamp = Get-Date -DisplayHint Time
  82.     "$timestamp $logentry" | Out-File $output -Append
  83. }
  84.  
  85.  
  86. #-------------------------------------------------
  87. #  Script
  88. #-------------------------------------------------
  89.  
  90. #Log file is overwritten each time the script is run to avoid
  91. #very large log files from growing over time
  92.  
  93. $timestamp = Get-Date -DisplayHint Time
  94. "$timestamp $logstring0" | Out-File $output
  95. Write-Logfile $logstring1
  96. Write-Logfile "  $date"
  97. Write-Logfile $logstring0
  98.  
  99.  
  100. #Check whether IIS Logs path exists, exit if it does not
  101. if ((Test-Path $Logpath) -ne $true)
  102. {
  103.     $tmpstring = "Log path $logpath not found"
  104.     Write-Warning $tmpstring
  105.     Write-Logfile $tmpstring
  106.     EXIT
  107. }
  108.  
  109.  
  110. $tmpstring = "Current Month: $currentmonth"
  111. Write-Host $tmpstring
  112. Write-Logfile $tmpstring
  113.  
  114. $tmpstring = "Previous Month: $previousmonth"
  115. Write-Host $tmpstring
  116. Write-Logfile $tmpstring
  117.  
  118. $tmpstring = "First Day of Previous Month: $firstdayofpreviousmonth"
  119. Write-Host $tmpstring
  120. Write-Logfile $tmpstring
  121.  
  122. #Fetch list of log files older than 1st day of previous month
  123. $logstoremove = Get-ChildItem -Path "$($Logpath)\*.*" -Include *.log | Where {$_.LastWriteTime -lt $firstdayofpreviousmonth -and $_.PSIsContainer -eq $false}
  124.  
  125. if ($($logstoremove.Count) -eq $null)
  126. {
  127.     $logcount = 0
  128. }
  129. else
  130. {
  131.     $logcount = $($logstoremove.Count)
  132. }
  133.  
  134. $tmpstring = "Found $logcount logs earlier than $firstdayofpreviousmonth"
  135. Write-Host $tmpstring
  136. Write-Logfile $tmpstring
  137.  
  138. #Init a hashtable to store list of log files
  139. $hashtable = @{}
  140.  
  141. #Add each logfile to hashtable
  142. foreach ($logfile in $logstoremove)
  143. {
  144.     $zipdate = $logfile.LastWriteTime.ToString("yyyy-MM")
  145.     $hashtable.Add($($logfile.FullName),"$zipdate")
  146. }
  147.  
  148. #Calculate unique yyyy-MM dates from logfiles in hashtable
  149. $hashtable = $hashtable.GetEnumerator() | Sort Value
  150. $dates = @($hashtable | Group -Property:Value | Select Name)
  151.  
  152. #For each yyyy-MM date add those logfiles to a zip file
  153. foreach ($date in $dates)
  154. {
  155.     $zipfilename = "$Logpath\$computername-$($date.Name).zip"
  156.  
  157.     if(-not (test-path($zipfilename)))
  158.     {
  159.         set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
  160.         (dir $zipfilename).IsReadOnly = $false
  161.     }
  162.  
  163.     $shellApplication = new-object -com shell.application
  164.     $zipPackage = $shellApplication.NameSpace($zipfilename)
  165.  
  166.     $zipfiles = $hashtable | Where {$_.Value -eq "$($date.Name)"}
  167.  
  168.     $tmpstring = "Zip file name is $zipfilename and will contain $($zipfiles.Count) files"
  169.     Write-Host $tmpstring
  170.     Write-Logfile $tmpstring
  171.  
  172.     foreach($file in $zipfiles)
  173.     {
  174.         $fn = $file.key.ToString()
  175.        
  176.         $tmpstring = "Adding $fn to $zipfilename"
  177.         Write-Host $tmpstring
  178.         Write-Logfile $tmpstring
  179.  
  180.         $zipPackage.CopyHere($fn,16)
  181.  
  182.         #This sleep interval helps avoids file lock/conflict issues. May need to increase if larger
  183.         #log files are taking longer to add to the zip file.
  184.         Start-sleep -s $sleepinterval
  185.     }
  186.  
  187.     #Compare count of log files on disk to count of log files in zip file
  188.     $zippedcount = ($zipPackage.Items()).Count
  189.    
  190.     $tmpstring = "Zipped count: $zippedcount"
  191.     Write-Host $tmpstring
  192.     Write-Logfile $tmpstring
  193.    
  194.     $tmpstring = "Files: $($zipfiles.Count)"
  195.     Write-Host $tmpstring
  196.     Write-Logfile $tmpstring
  197.  
  198.     #If counts match it is safe to delete the log files from disk
  199.     if ($zippedcount -eq $($zipfiles.Count))
  200.     {
  201.         $tmpstring = "Zipped file count matches log file count, safe to delete log files"
  202.         Write-Host $tmpstring
  203.         Write-Logfile $tmpstring
  204.         foreach($file in $zipfiles)
  205.         {
  206.             $fn = $file.key.ToString()
  207.             Remove-Item $fn
  208.         }
  209.  
  210.         #If archive path was specified move zip file to archive path
  211.         if ($ArchivePath)
  212.         {
  213.             #Check whether archive path is accessible
  214.             if ((Test-Path $ArchivePath) -ne $true)
  215.             {
  216.                 $tmpstring = "Log path $archivepath not found or inaccessible"
  217.                 Write-Warning $tmpstring
  218.                 Write-Logfile $tmpstring
  219.             }
  220.             else
  221.             {
  222.                 #Check if subfolder of archive path exists
  223.                 if ((Test-Path $ArchivePath\$computername) -ne $true)
  224.                 {
  225.                     try
  226.                     {
  227.                         #Create subfolder based on server name
  228.                         New-Item -Path $ArchivePath\$computername -ItemType Directory -ErrorAction STOP
  229.                     }
  230.                     catch
  231.                     {
  232.                         #Subfolder creation failed
  233.                         $tmpstring = "Unable to create $computername subfolder in $archivepath"
  234.                         Write-Host $tmpstring
  235.                         Write-Logfile $tmpstring
  236.  
  237.                         $tmpstring = $_.Exception.Message
  238.                         Write-Warning $tmpstring
  239.                         Write-Logfile $tmpstring
  240.                     }
  241.                 }
  242.  
  243.                 try
  244.                 {
  245.                     #Move the zip file
  246.                     Move-Item $zipfilename -Destination $ArchivePath\$computername -ErrorAction STOP
  247.                     $tmpstring = "$zipfilename was moved to $archivepath\$computername"
  248.                     Write-Host $tmpstring
  249.                     Write-Logfile $tmpstring
  250.                 }
  251.                 catch
  252.                 {
  253.                     #Move failed, log the error
  254.                     $tmpstring = "Unable to move $zipfilename to $ArchivePath\$computername"
  255.                     Write-Host $tmpstring
  256.                     Write-Logfile $tmpstring
  257.                     Write-Warning $_.Exception.Message
  258.                     Write-Logfile $_.Exception.Message
  259.                 }  
  260.             }
  261.         }
  262.  
  263.     }
  264.     else
  265.     {
  266.         $tmpstring = "Zipped file count does not match log file count, not safe to delete log files"
  267.         Write-Host $tmpstring
  268.         Write-Logfile $tmpstring
  269.     }
  270.  
  271. }
  272.  
  273.  
  274. #Finished
  275. $tmpstring = "Finished"
  276. Write-Host $tmpstring
  277. Write-Logfile $tmpstring
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement