Parsing IIS logs from PowerShell
Dec. 18th, 2014 03:01 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Posted because there's no official way of converting IIS W3C logs to PowerShell objects, and the original script I found wasn't quite doing what I wanted.
# Define the location of log files and a temporary file
$LogFolder = "build1:\Logs\iis\W3SVC1\"
$LogFiles = ls "$logFolder\u_ex*.log" #Ensure we only get the correctly formatted log files if there's a mixture of styles
# Logs will store each line of the log files in an array
$Logs = @()
# Skip the comment lines
$LogFiles | % { Get-Content $_ | where {$_ -notLike "#[D,F,S,V]*" } | % { $Logs += $_ } }
# Then grab the first header line, and adjust its format for later
$LogColumns = ( $LogFiles | select -first 1 | % { Get-Content $_ | where {$_ -Like "#[F]*" } } ) `
-replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)",""
$newLine = "`r`n"
$tempCsv = "$($LogColumns[0])$newline$($Logs -join $newline)"
return $tempCsv | ConvertFrom-Csv -Delimiter " "
# Define the location of log files and a temporary file
$LogFolder = "build1:\Logs\iis\W3SVC1\"
$LogFiles = ls "$logFolder\u_ex*.log" #Ensure we only get the correctly formatted log files if there's a mixture of styles
# Logs will store each line of the log files in an array
$Logs = @()
# Skip the comment lines
$LogFiles | % { Get-Content $_ | where {$_ -notLike "#[D,F,S,V]*" } | % { $Logs += $_ } }
# Then grab the first header line, and adjust its format for later
$LogColumns = ( $LogFiles | select -first 1 | % { Get-Content $_ | where {$_ -Like "#[F]*" } } ) `
-replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)",""
$newLine = "`r`n"
$tempCsv = "$($LogColumns[0])$newline$($Logs -join $newline)"
return $tempCsv | ConvertFrom-Csv -Delimiter " "