Heya all – here are a couple of quick functions to help analyze logs files. Coming from a ConfigMgr/SCCM background, I got used to reading a LOT of logs. Having a couple of functions like this would have greatly helped!
First – let’s see if there are warning and/or error messages in a log (or stack of logs)
function Analyze-LogContent {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$LogFilePath,
[string]$ErrorPattern = 'ERROR|Error|error',
[string]$WarningPattern = 'WARNING|Warning|warning'
)
if (-not (Test-Path -Path $LogFilePath)) {
Write-Error "Log file does not exist at the path: $LogFilePath"
return
}
# Reading the log file
$logContent = Get-Content -Path $LogFilePath
# Analyzing for errors
$errors = $logContent | Where-Object { $_ -match $ErrorPattern }
$warnings = $logContent | Where-Object { $_ -match $WarningPattern }
# Output analysis
$output = @()
if ($errors.Count -gt 0) {
$output += "Found $($errors.Count) errors in the log."
} else {
$output += "No errors found in the log."
}
if ($warnings.Count -gt 0) {
$output += "Found $($warnings.Count) warnings in the log."
} else {
$output += "No warnings found in the log."
}
return $output
}
# Example usage
$logPath = "C:\Path\To\Your\LogFile.log"
$result = Analyze-LogContent -LogFilePath $logPath
$result | ForEach-Object { Write-Host $_ }
Change the patterns as necessary – ERR, for example.
The second function is pretty straight forward – summarize a log counting the number of INFO, Warning, and Error messages:
function Summarize-LogFile {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$LogFilePath
)
if (-not (Test-Path -Path $LogFilePath)) {
Write-Error "Log file does not exist at the path: $LogFilePath"
return
}
$logContent = Get-Content -Path $LogFilePath
$infoCount = 0
$errorCount = 0
$warningCount = 0
foreach ($line in $logContent) {
switch -Regex ($line) {
"INFO" { $infoCount++ }
"ERROR" { $errorCount++ }
"WARNING" { $warningCount++ }
}
}
$summary = @"
Log File Summary:
Info Entries: $infoCount
Error Entries: $errorCount
Warning Entries: $warningCount
Total Entries: $($logContent.Count)
"@
return $summary
}
# Example usage
$logPath = "C:\Path\To\Your\LogFile.log"
$summary = Summarize-LogFile -LogFilePath $logPath
Write-Host $summary
There ya go! I will keep adding to these, and eventually get them in Github so you all can tell me how wrong they are 🙂
Happy Coding!