# Shutdown info collection script - Run as Administrator for full event log access
# All output is saved to a .txt file in the same folder

$ReportDir = $PSScriptRoot
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$ReportFile = Join-Path $ReportDir "ShutdownReport_$Timestamp.txt"

function Write-Report {
    param([string]$Text, [string]$Section = "")
    if ($Section) { $script:Report += "`n========== $Section ==========`n" }
    $script:Report += $Text + "`n"
}

$Report = ""
Write-Report "Shutdown Analysis Report" "Header"
Write-Report "Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Report "Computer: $env:COMPUTERNAME"
Write-Report "User: $env:USERNAME"

# System info
Write-Report "" "System Info"
try {
    $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
    if ($os) {
        Write-Report "OS: $($os.Caption) (Version $($os.Version))"
        Write-Report "Last boot: $($os.LastBootUpTime)"
        Write-Report "Uptime: $((New-TimeSpan -Start $os.LastBootUpTime -End (Get-Date)).ToString())"
    }
} catch { Write-Report "Failed to get system info: $_" }

# Event ID descriptions
$ShutdownEventIds = @{
    41 = "Kernel-Power: System did not shut down cleanly (power loss/BSOD/forced)"
    1074 = "User or process initiated shutdown/restart"
    6006 = "Event log service stopped (written on normal shutdown)"
    6008 = "Unexpected shutdown - previous shutdown was unexpected"
    109 = "Kernel-Power: Critical battery/power event"
    1 = "Kernel-Power: Wake from sleep"
    42 = "Kernel-Power: System entering sleep"
}

Write-Report "" "Event ID Reference"
foreach ($id in ($ShutdownEventIds.Keys | Sort-Object)) {
    Write-Report "  Event ID $id : $($ShutdownEventIds[$id])"
}

# 1. Unexpected shutdown (6008)
Write-Report "" "[IMPORTANT] Unexpected shutdowns (Event 6008)"
try {
    $events6008 = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6008 } -MaxEvents 50 -ErrorAction SilentlyContinue
    if ($events6008) {
        foreach ($e in $events6008) {
            Write-Report "  Time: $($e.TimeCreated) | Unexpected shutdown"
        }
    } else { Write-Report "  No 6008 records found (or run as Administrator)" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 2. Kernel-Power 41 - unclean shutdown
Write-Report "" "[IMPORTANT] Unclean shutdown / power loss (Event 41)"
try {
    $events41 = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 41; ProviderName = 'Microsoft-Windows-Kernel-Power' } -MaxEvents 30 -ErrorAction SilentlyContinue
    if ($events41) {
        foreach ($e in $events41) {
            Write-Report "  Time: $($e.TimeCreated)"
            if ($e.Properties.Count -ge 1) { Write-Report "     BugcheckCode: $($e.Properties[0].Value)" }
        }
    } else { Write-Report "  No Event 41 records" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 3. Shutdown/restart source (1074)
Write-Report "" "Shutdown/Restart source (Event 1074)"
try {
    $events1074 = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 1074 } -MaxEvents 20 -ErrorAction SilentlyContinue
    if ($events1074) {
        foreach ($e in $events1074) {
            $props = $e.Properties
            $who = ""
            for ($i = 0; $i -lt $props.Count; $i++) { $who += $props[$i].Value; if ($i -lt $props.Count - 1) { $who += " | " } }
            Write-Report "  Time: $($e.TimeCreated) | $who"
        }
    } else { Write-Report "  No 1074 records" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 4. Event log service stopped (6006) - one per shutdown
Write-Report "" "Shutdown timeline (Event 6006)"
try {
    $events6006 = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6006 } -MaxEvents 30 -ErrorAction SilentlyContinue
    if ($events6006) {
        foreach ($e in $events6006) {
            Write-Report "  Shutdown time: $($e.TimeCreated)"
        }
    } else { Write-Report "  No 6006 records" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 5. BugCheck / BSOD
Write-Report "" "BugCheck / BSOD (Event 1001)"
try {
    $events1001 = Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-WER-Diag/Operational'; Id = 1001 } -MaxEvents 10 -ErrorAction SilentlyContinue
    if ($events1001) {
        foreach ($e in $events1001) {
            Write-Report "  Time: $($e.TimeCreated) | $($e.Message)"
        }
    } else { Write-Report "  No WER BugCheck records" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 6. Recent system errors (last 7 days)
Write-Report "" "Recent system errors/warnings (last 7 days)"
try {
    $cutoff = (Get-Date).AddDays(-7)
    $critical = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2,3 } -MaxEvents 30 -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $cutoff }
    if ($critical) {
        foreach ($e in $critical) {
            $msgLen = [Math]::Min(120, $e.Message.Length)
            Write-Report "  $($e.TimeCreated) | ID:$($e.Id) | $($e.ProviderName) | $($e.Message.Substring(0, $msgLen))..."
        }
    } else { Write-Report "  No recent critical events" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# 7. Power / thermal
Write-Report "" "Kernel-Power events"
try {
    $power = Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power' } -MaxEvents 20 -ErrorAction SilentlyContinue
    if ($power) {
        foreach ($e in $power) {
            $msgLen = [Math]::Min(100, $e.Message.Length)
            Write-Report "  $($e.TimeCreated) | ID:$($e.Id) | $($e.Message.Substring(0, $msgLen))"
        }
    } else { Write-Report "  No Kernel-Power events" }
} catch { Write-Report "  Read failed: $($_.Exception.Message)" }

# Write to txt file
$Report | Set-Content -Path $ReportFile -Encoding UTF8 -NoNewline
if (Test-Path $ReportFile) {
    Write-Host "Report saved to: $ReportFile" -ForegroundColor Green
    Write-Host "Open the .txt file with Notepad to view." -ForegroundColor Yellow
} else {
    Write-Host "Save failed." -ForegroundColor Red
}
