Get-EventLogSummary.ps1
|
<#PSScriptInfo
.VERSION 1.0.0 .GUID cce6bb5a-84a6-5024-bd60-6273a68efd5b .AUTHOR Torsten Weise .COMPANYNAME powerscripting.de .COPYRIGHT (c) 2026 Torsten Weise. MIT-Lizenz. .TAGS Powerscripting German Monitoring Report Windows Backup EventLog Journal Ollama AI LLM Linux PSEdition_Core PSEdition_Desktop .LICENSEURI https://powerscripting.de/skripte/files/LICENSE.txt .PROJECTURI https://powerscripting.de/skripte/get-eventlogsummary.html .ICONURI https://powerscripting.de/assets/icon-192.png .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES Erste Veröffentlichung in der PowerShell Gallery. .PRIVATEDATA #> <# .SYNOPSIS Fasst Fehler aus der Windows-Ereignisanzeige oder dem Linux-Journal mit einer lokalen KI (Ollama) zusammen. .DESCRIPTION Wer morgens 300 Fehlereinträge vor sich hat, liest keinen davon. Dieses Skript sammelt die Fehler und kritischen Ereignisse der letzten Stunden, fasst gleiche Meldungen zusammen (Zahlen, GUIDs und Zeitstempel werden dafür vereinheitlicht) und schickt die häufigsten Gruppen an ein Sprachmodell in Ollama. Zurück kommt eine kurze Lage auf Deutsch: was wichtig ist, was warten kann, was als Nächstes zu tun ist. Die Daten verlassen das eigene Netz nicht, wenn Ollama lokal oder im Homelab läuft. Mit -Mask werden IP-Adressen, E-Mail-Adressen und Kontonamen vor dem Versand zusätzlich durch Platzhalter ersetzt. Quellen: - Windows: Ereignisprotokolle System und Application (änderbar mit -LogName), Stufen Kritisch und Fehler, mit -IncludeWarning auch Warnungen. - Linux: systemd-Journal über journalctl, Priorität err und höher, mit -IncludeWarning auch warning. - Datei: JSON mit Ereignissen (Felder TimeCreated, Level, Provider, Id, Message), etwa aus einem anderen System oder einer früheren Sammlung mit -SaveEvents. Ergebnis: HTML- und Markdown-Bericht im Ordner -ReportPath mit der Zusammenfassung und allen Gruppen. Mit -PassThru zusätzlich die Gruppen als Objekte. Ohne erreichbares Ollama entsteht der Bericht ohne KI-Teil und das Skript endet mit Exitcode 1. .PARAMETER Hours Zeitraum in Stunden bis jetzt. Standard: 24. .PARAMETER LogName Windows-Protokolle. Standard: System, Application. .PARAMETER IncludeWarning Auch Warnungen auswerten. .PARAMETER InputPath Ereignisse aus einer JSON-Datei statt aus dem lokalen System lesen. .PARAMETER SaveEvents Gesammelte Ereignisse zusätzlich als JSON speichern. .PARAMETER OllamaUrl Adresse von Ollama. Standard: Umgebungsvariable OLLAMA_HOST oder http://localhost:11434. .PARAMETER Model Sprachmodell in Ollama. Standard: gemma3:4b, läuft auch ohne Grafikkarte. Mit GPU liefert gemma3:12b oder qwen3:14b bessere Ergebnisse. .PARAMETER MaxGroups Höchstens so viele Gruppen gehen an das Modell, die häufigsten zuerst. Standard: 25. .PARAMETER Mask IP-Adressen, E-Mail-Adressen und Kontonamen vor dem Versand an das Modell ersetzen. .PARAMETER NoAi Nur sammeln und gruppieren, kein Sprachmodell aufrufen. .PARAMETER ReportPath Ordner für die Berichte. Standard: aktueller Ordner. .PARAMETER PassThru Gruppen zusätzlich als Objekte ausgeben. .EXAMPLE .\Get-EventLogSummary.ps1 Fehler der letzten 24 Stunden mit Ollama auf demselben Rechner zusammenfassen. .EXAMPLE .\Get-EventLogSummary.ps1 -OllamaUrl http://ollama.lan:11434 -Model gemma3:12b -Mask -Hours 72 -ReportPath \\fs01\it\logs Wochenend-Rückblick mit einem stärkeren Modell im Homelab, Kontonamen und Adressen maskiert. .EXAMPLE pwsh ./Get-EventLogSummary.ps1 -IncludeWarning -ReportPath /var/www/html/logs Unter Linux das Journal inklusive Warnungen auswerten, etwa täglich per systemd-Timer. .NOTES Autor: Torsten Weise, powerscripting.de Windows PowerShell 5.1 oder PowerShell 7, unter Linux PowerShell 7 und journalctl. Ollama ab Version 0.5. Für das Sicherheitsprotokoll und manche Journale sind Administrator- bzw. root-Rechte nötig. #> [CmdletBinding()] param( [ValidateRange(1, 720)] [int] $Hours = 24, [string[]] $LogName = @('System', 'Application'), [switch] $IncludeWarning, [string] $InputPath, [string] $SaveEvents, [string] $OllamaUrl, [string] $Model = 'gemma3:4b', [ValidateRange(1, 200)] [int] $MaxGroups = 25, [switch] $Mask, [switch] $NoAi, [string] $ReportPath = (Get-Location).Path, [switch] $PassThru ) $ErrorActionPreference = 'Stop' if (-not $OllamaUrl) { $OllamaUrl = if ($env:OLLAMA_HOST) { $env:OLLAMA_HOST } else { 'http://localhost:11434' } } if ($OllamaUrl -notmatch '^https?://') { $OllamaUrl = "http://$OllamaUrl" } $OllamaUrl = $OllamaUrl.TrimEnd('/') $since = (Get-Date).AddHours(-$Hours) $onWindows = ($PSVersionTable.PSVersion.Major -lt 6) -or $IsWindows # ---------- Ereignisse sammeln ---------- function Get-WindowsEventEntry { $levels = @(1, 2); if ($IncludeWarning) { $levels += 3 } $names = @{ 1 = 'Kritisch'; 2 = 'Fehler'; 3 = 'Warnung' } foreach ($l in $LogName) { try { $ev = Get-WinEvent -FilterHashtable @{ LogName = $l; Level = $levels; StartTime = $since } -ErrorAction Stop } catch { if ($_.FullyQualifiedErrorId -match 'NoMatchingEventsFound') { continue } Write-Warning "$l nicht lesbar: $($_.Exception.Message)"; continue } foreach ($e in $ev) { $msg = $e.Message; if (-not $msg) { $msg = "(keine Beschreibung, Ereignis-ID $($e.Id))" } [pscustomobject]@{ TimeCreated = $e.TimeCreated.ToString('s'); Level = $names[[int]$e.Level]; Log = $l; Provider = $e.ProviderName; Id = "$($e.Id)"; Message = $msg } } } } function Get-JournalEntry { if (-not (Get-Command journalctl -ErrorAction SilentlyContinue)) { throw 'journalctl nicht gefunden.' } $prio = if ($IncludeWarning) { 'warning' } else { 'err' } $names = @{ '0' = 'Kritisch'; '1' = 'Kritisch'; '2' = 'Kritisch'; '3' = 'Fehler'; '4' = 'Warnung' } $lines = & journalctl --since ('{0:yyyy-MM-dd HH:mm:ss}' -f $since) -p $prio -o json --no-pager 2>$null foreach ($line in $lines) { if (-not $line) { continue } try { $j = $line | ConvertFrom-Json } catch { continue } $m = $j.MESSAGE if ($m -is [array]) { $m = [Text.Encoding]::UTF8.GetString([byte[]]$m) } # Binärmeldungen $src = if ($j.SYSLOG_IDENTIFIER) { $j.SYSLOG_IDENTIFIER } elseif ($j._SYSTEMD_UNIT) { $j._SYSTEMD_UNIT } else { $j._COMM } $t = [DateTimeOffset]::FromUnixTimeMilliseconds([long]$j.__REALTIME_TIMESTAMP / 1000).LocalDateTime [pscustomobject]@{ TimeCreated = $t.ToString('s'); Level = $names["$($j.PRIORITY)"]; Log = 'journal'; Provider = "$src"; Id = "$($j._SYSTEMD_UNIT)"; Message = "$m" } } } if ($InputPath) { # ForEach-Object entpackt das Array, Windows PowerShell 5.1 liefert es sonst als ein Objekt $events = @(Get-Content -LiteralPath $InputPath -Raw -Encoding UTF8 | ConvertFrom-Json | ForEach-Object { $_ }) $hostName = [IO.Path]::GetFileNameWithoutExtension($InputPath) } else { $events = @(if ($onWindows) { Get-WindowsEventEntry } else { Get-JournalEntry }) $hostName = [Environment]::MachineName } if ($SaveEvents) { $events | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $SaveEvents -Encoding UTF8 } # ---------- Gruppieren ---------- function Get-Template([string] $Text) { $t = $Text -replace '\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?', '<GUID>' $t = $t -replace '\b0x[0-9a-fA-F]+\b', '<HEX>' $t = $t -replace '\b(?:\d{1,3}\.){3}\d{1,3}\b', '<IP>' $t = $t -replace '\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z?\b', '<ZEIT>' $t = $t -replace '\b\d{1,2}\.\d{1,2}\.\d{2,4}( \d{1,2}:\d{2}(:\d{2})?)?\b', '<ZEIT>' $t = $t -replace '\b\d+\b', '<N>' $t = $t -replace '\s+', ' ' return $t.Trim() } $groups = @($events | Group-Object { "$($_.Provider)|$($_.Id)|" + (Get-Template "$($_.Message)").Substring(0, [Math]::Min(200, (Get-Template "$($_.Message)").Length)) } | ForEach-Object { $g = @($_.Group | Sort-Object TimeCreated) $lv = if ($g.Level -contains 'Kritisch') { 'Kritisch' } elseif ($g.Level -contains 'Fehler') { 'Fehler' } else { 'Warnung' } $first = $g[0] [pscustomobject]@{ Count = $g.Count; Level = $lv; Log = $first.Log; Provider = $first.Provider; Id = $first.Id First = $first.TimeCreated; Last = $g[-1].TimeCreated Message = ("$($g[-1].Message)" -replace '\s+', ' ').Trim() } } | Sort-Object @{ e = { @{ 'Kritisch' = 0; 'Fehler' = 1; 'Warnung' = 2 }[$_.Level] } }, @{ e = 'Count'; Descending = $true }) # ---------- Maskieren ---------- $maskMap = [ordered]@{} function Protect-Text([string] $Text) { if (-not $Mask) { return $Text } $rules = @( @{ P = '\b[\w.+-]+@[\w-]+(\.[\w-]+)+\b'; N = 'MAIL' }, @{ P = '\b(?:\d{1,3}\.){3}\d{1,3}\b'; N = 'IP' }, @{ P = '\b[A-Za-z][\w-]{1,14}\\[\w.$-]+'; N = 'KONTO' } ) foreach ($r in $rules) { $Text = [regex]::Replace($Text, $r.P, { param($m) if (-not $maskMap.Contains($m.Value)) { $maskMap[$m.Value] = '{0}-{1}' -f $r.N, (@($maskMap.Values | Where-Object { $_ -like "$($r.N)-*" }).Count + 1) } $maskMap[$m.Value] }) } return $Text } # ---------- Sprachmodell ---------- $summary = $null; $aiError = $null $sent = @($groups | Select-Object -First $MaxGroups) if (-not $NoAi -and $groups.Count) { $lines = foreach ($g in $sent) { $msg = Protect-Text $g.Message if ($msg.Length -gt 600) { $msg = $msg.Substring(0, 600) + ' …' } "- {0}x {1} | {2} | Quelle {3} | ID {4} | zuerst {5}, zuletzt {6} | {7}" -f $g.Count, $g.Level, $g.Log, $g.Provider, $g.Id, $g.First, $g.Last, $msg } $system = @' Du bist ein erfahrener Administrator für Windows und Linux. Du bekommst gruppierte Fehlerereignisse eines Rechners. Antworte auf Deutsch, knapp und sachlich, in genau diesen Abschnitten: ## Lage Ein bis zwei Sätze: Ist der Rechner in Ordnung, gestört oder ernsthaft gefährdet? ## Wichtig Höchstens fünf Punkte. Je Punkt: was passiert, Quelle und Ereignis-ID, Häufigkeit, warum es zählt. ## Kann warten Bekannte harmlose oder kosmetische Meldungen in einem kurzen Absatz. ## Nächste Schritte Höchstens fünf konkrete Prüfungen oder Befehle, die wichtigsten zuerst. Erfinde keine Ursachen. Wenn die Meldungen nicht ausreichen, sag das. Platzhalter wie IP-1 oder KONTO-2 übernimmst du unverändert. '@ $user = "Rechner: $hostName`nZeitraum: letzte $Hours Stunden bis $(Get-Date -Format 'dd.MM.yyyy HH:mm')`n$($events.Count) Ereignisse in $($groups.Count) Gruppen, hier die $($sent.Count) wichtigsten:`n" + ($lines -join "`n") $body = @{ model = $Model; stream = $false messages = @(@{ role = 'system'; content = $system }, @{ role = 'user'; content = $user }) options = @{ temperature = 0.2; num_ctx = 8192 } } | ConvertTo-Json -Depth 5 try { $r = Invoke-RestMethod -Uri "$OllamaUrl/api/chat" -Method Post -Body ([Text.Encoding]::UTF8.GetBytes($body)) -ContentType 'application/json; charset=utf-8' -TimeoutSec 600 $summary = ("$($r.message.content)" -replace '(?s)<think>.*?</think>', '').Trim() if (-not $summary) { $aiError = 'Das Modell hat eine leere Antwort geliefert.' } } catch { $aiError = "Ollama unter $OllamaUrl nicht erreichbar oder Modell $Model fehlt: $($_.Exception.Message)" Write-Warning $aiError } } # ---------- Bericht ---------- if (-not (Test-Path -LiteralPath $ReportPath)) { New-Item -ItemType Directory -Path $ReportPath -Force | Out-Null } $stamp = Get-Date -Format 'yyyy-MM-dd_HHmm' $base = Join-Path $ReportPath "Logbericht_${hostName}_$stamp" function Enc([string] $s) { return [System.Net.WebUtility]::HtmlEncode($s) } function ConvertTo-SimpleHtml([string] $Md) { $out = New-Object System.Collections.Generic.List[string]; $inList = $false foreach ($l in ($Md -split "`r?`n")) { $isItem = $l -match '^\s*([-*]|\d+\.)\s+(.*)$' if ($inList -and -not $isItem) { $out.Add('</ul>'); $inList = $false } if ($l -match '^#{1,6}\s+(.*)$') { $out.Add("<h3>$(Enc $Matches[1])</h3>") } elseif ($isItem) { if (-not $inList) { $out.Add('<ul>'); $inList = $true }; $out.Add("<li>$(Enc $Matches[2])</li>") } elseif ($l.Trim()) { $out.Add("<p>$(Enc $l)</p>") } } if ($inList) { $out.Add('</ul>') } return (($out -join "`n") -replace '\*\*([^*]+)\*\*', '<b>$1</b>' -replace '`([^`]+)`', '<code>$1</code>') } $crit = @($groups | Where-Object Level -eq 'Kritisch' | Measure-Object Count -Sum).Sum $err = @($groups | Where-Object Level -eq 'Fehler' | Measure-Object Count -Sum).Sum $aiBlock = if ($summary) { ConvertTo-SimpleHtml $summary } elseif ($NoAi) { '<p>Ohne KI-Zusammenfassung erstellt (-NoAi).</p>' } elseif (-not $groups.Count) { '<p>Keine Fehler im Zeitraum. Nichts zu tun.</p>' } else { "<p class='err'>$(Enc $aiError)</p>" } $rows = foreach ($g in $groups) { $cls = switch ($g.Level) { 'Kritisch' { 'c' } 'Fehler' { 'w' } default { 'i' } } "<tr class='$cls'><td>$($g.Count)</td><td>$(Enc $g.Level)</td><td>$(Enc $g.Log)</td><td>$(Enc $g.Provider)</td><td>$(Enc $g.Id)</td><td>$(Enc $g.Last)</td><td>$(Enc ($g.Message.Substring(0, [Math]::Min(400, $g.Message.Length))))</td></tr>" } $modelNote = if ($summary) { "Zusammenfassung von $(Enc $Model) über $(Enc $OllamaUrl)$(if ($Mask) { ', Kontonamen und Adressen maskiert' }). KI-Text kann Fehler enthalten, die Tabelle darunter ist die Quelle." } else { '' } $html = @" <!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><title>Logbericht $(Enc $hostName)</title> <style>body{font:14px/1.55 Segoe UI,Arial,sans-serif;margin:24px;color:#1b2433;max-width:1200px}h1{margin:0 0 4px} .ai{border:1px solid #c9d6ea;border-left:4px solid #2f8bff;border-radius:8px;padding:6px 18px;background:#f6f9ff;margin:16px 0}.ai h3{margin:14px 0 4px} table{border-collapse:collapse;width:100%;margin:12px 0 28px}th,td{border:1px solid #d5dbe5;padding:5px 8px;text-align:left;vertical-align:top}th{background:#0f1b2e;color:#fff} tr.c td:nth-child(2){background:#fde2e1;color:#9b1c1c;font-weight:600}tr.w td:nth-child(2){background:#fff4d6;color:#8a5a00}tr.i td:nth-child(2){background:#e8f1ff} .err{color:#9b1c1c}.note{color:#5b6678;font-size:12px}code{background:#eef2f7;padding:1px 4px;border-radius:4px}</style></head><body> <h1>Logbericht $(Enc $hostName)</h1><p>Letzte $Hours Stunden bis $(Get-Date -Format 'dd.MM.yyyy HH:mm'): $($events.Count) Ereignisse in $($groups.Count) Gruppen, davon $([int]$crit) kritisch und $([int]$err) Fehler.</p> <div class="ai">$aiBlock<p class="note">$modelNote</p></div> <h2>Alle Gruppen</h2><table><tr><th>Anzahl</th><th>Stufe</th><th>Protokoll</th><th>Quelle</th><th>ID</th><th>Zuletzt</th><th>Meldung (letzte)</th></tr>$($rows -join "`n")</table> <p class="note">Erstellt mit Get-EventLogSummary.ps1 von powerscripting.de</p></body></html> "@ [System.IO.File]::WriteAllText("$base.html", $html, (New-Object System.Text.UTF8Encoding($true))) $md = "# Logbericht $hostName`n`nLetzte $Hours Stunden: $($events.Count) Ereignisse in $($groups.Count) Gruppen.`n`n" + $(if ($summary) { "$summary`n`n" } elseif ($aiError) { "_$($aiError)_`n`n" } else { '' }) + "| Anzahl | Stufe | Quelle | ID | Meldung |`n|---|---|---|---|---|`n" + (($groups | ForEach-Object { "| $($_.Count) | $($_.Level) | $($_.Provider) | $($_.Id) | $(($_.Message.Substring(0, [Math]::Min(160, $_.Message.Length))) -replace '\|', '/') |" }) -join "`n") [System.IO.File]::WriteAllText("$base.md", $md, (New-Object System.Text.UTF8Encoding($false))) Write-Host ("{0}: {1} Ereignisse, {2} Gruppen" -f $hostName, $events.Count, $groups.Count) -ForegroundColor $(if ($crit) { 'Red' } elseif ($err) { 'Yellow' } else { 'Green' }) if ($summary) { Write-Host ''; Write-Host $summary; Write-Host '' } Write-Host "Bericht: $base.html" if ($PassThru) { $groups } if ($aiError) { exit 1 } else { exit 0 } |