If you don’t waste your server’s disk space to store IIS Log files then you can create a scheduled task and let the files to be compressed automatically. So we need a piece of code to compress log files and a scheduled task to run the code periodically.
1st step – here is our small powershell code. Copy & save it as “compress-iis-logs.ps1” without quotes.
$LogDir = "C:\inetpub\logs\LogFiles" $DaysBefore = 7 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 $DaysBefore) { #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
2nd step – allow powershell to run unsigned codes to run by executing the code below in Powershell.
set-executionpolicy remotesigned
3rd step – create a new basic daily scheduled task. Choose “Start a program” and click next, type “powershell.exe” (without quotes) for the input of Program/Script then on the “Add arguments” side (below) type the full path and name of your compress-iis-logs.ps1 file. For an instance “C:\inetpub\scripts\compress-iis-logs.ps1” without qouotes.
Everything is ok, now your system is able to compress log files automatically.
1 Comment
Javichol
I run your script but something is hapennning, i have olds logs from the last year, when it runs compress like 5 o 10 files and then still runnning but nothing in compressin, so i have to run it again and again, did you know why these could be happening?