TheGeekery

The Usual Tech Ramblings

PowerShell: Cleaning Up IIS Logs

This one is a quick and easy one. We have multiple IIS boxes, which each generate large usage logs on a daily basis. To save space, and for analytics off-server, we compress the log files. Having found Rar is one of the better compression algorithms, we simply shell out to rar, compress the logs, and cleanup older logs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$winrar = 'd:\program files\winrar\rar.exe'

$path = $args[0]

Get-ChildItem $path -recurse | where{$_.Extension -match "log"} | Foreach-Object `
{
    $log_name = $_.FullName
    $rar_name = $log_name.Replace(".log", ".rar")

    $args = "-ri1 m $rar_name $log_name"

    [Diagnostics.Process]::Start($winrar, $args)

    Start-Sleep -s 5

}

$date = Get-Date
$month = $date.Month
$year = $date.Year

$new_date = Get-Date "$month/01/$year"
$log_date = $new_date.AddMonths(-3)

Get-ChildItem $path -recurse | Where { $_.Extension -match "rar" -and $_.LastWriteTime -le $log_date} | ForEach-Object {
  Remove-Item $_.FullName
}

This could probably do with some cleaning up as there are probably some slightly more efficient ways of doing some of this, but it works.

Comments