Archiving IIS Logs with Powershell

Posted on 1 maart 2012 | Category :Nieuws | Geen reacties op Archiving IIS Logs with Powershell

A commonly asked question about IIS I read many times is: is there an easy way to archive IIS logs. After reading many forums and blogs I couldn’t find something that does this job for me.

This script uses 7zip to compress the files, and since logfiles are plain-text only, the compress-ratio is pretty good.

Requirements:

  • Windows Powershell modules installed
  • 7zip installed (http://www.7-zip.org/)

Code:

param([string]$Path = $(read-host "Enter the path"))
function New-Zip
{
    param([string]$zipfilename)
    set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipfilename).IsReadOnly = $false
}

function Create-7zip([String] $aDirectory, [String] $aZipfile){
	[String]$pathToZipExe = "C:\Program Files\7-Zip\7z.exe"
	[Array]$arguments = "A", "-tzip", "$aZipfile", "$aDirectory"
	& $pathToZipExe $arguments;
}
	
function Add-Zip
{
    param([string]$zipfilename)

    if(-not (test-path($zipfilename)))
    {
	echo "$zipfilename"
        set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
        (dir $zipfilename).IsReadOnly = $false  
    }

    foreach($file in $input) 
    { 
		Create-7Zip $file.Fullname $zipfilename    
    }
}
$FilesToZip = dir $Path -recurse -include *.log
foreach ($file in $FilesToZip) {
	dir $($file.directoryname+"\"+$file.name) | Add-zip $($file.directoryname+".zip") | Out-Null
}

foreach ($file in $FilesToZip) {
	del $($file.directoryname+"\"+$file.name)
}

Usage:

  • Specify the location of 7zip at $pathToZipExe
  • Run the script: .\script.ps1
  • Specify the location of the root-dir that contains the log file directory.

In my case all log files are saved in: D:\HTTPLogs\ under subdirectories called: W3SVC1 (where 1 is the ID of the website). In my case the location I have to specify is: D:\HTTPLogs

The script will create a compressed file for each subdirectory in D:\HTTPLogs, put the logs file in it, and then remove the logfiles that archived.

» Tags: , , , ,

Comments 0

Geef een antwoord