In my short search for a script which can compress IIS log files i couldn’t find any solution (written in powershell). So i made my one myself. The script compresses all .log files located in the sub directories of $LogDir and files newer than 5 days are skipped. The script uses the zip functionality present in windows so no external programs are needed. The script was tested on Windows 2008 Server R2.
$LogDir = "D:\Logs"
function Zip-Logs
{
foreach($Dir in Get-ChildItem $LogDir | ?{ $_.PSIsContainer } )
{
foreach ($file in Get-ChildItem -Filter *.log $Dir.FullName)
{
$TimeSpan = New-TimeSpan ($file.LastWriteTime) (Get-Date)
$filename = $file.FullName + ".zip"
if ($TimeSpan.TotalDays -gt 5)
{
#Create Zip
New-Zip -zipfilename $filename
#Add file
$file | Add-Zip -zipfilename $filename
#Delete the uncompressed file
$file.Delete()
}
}
}
}
function Add-Zip
{
param([string]$zipfilename)
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)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
#This waits for the zip operation to finish
while($zipPackage.Items().Item($file.Name) -Eq $null)
{
start-sleep -m 10
}
}
}
function New-Zip
{
param([string]$zipfilename)
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
Zip-Logs