SystemHealthCheck.ps1

<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID 842a8b56-a4d0-4cad-8f89-55d9e27a28b8
 
.AUTHOR waresoft
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS PowerShell Automation
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
 
#>

<#
 
.DESCRIPTION
This is a script to run light maintenance cleanup tasks on your pc and get system security and health metrics, update Windows Defender signatures and present it all in a HTML file on your desktop to view.
 
#>


<#
.SYNOPSIS
    Comprehensive Windows 11 Weekly Health Check & Maintenance (Auto-Elevating + HTML Export)
.DESCRIPTION
    Self-elevates to Administrator, audits OS uptime, pending reboot flags, CPU/RAM load,
    storage health/wear, auto-start services, network connectivity, VBS/Credential Guard/LSA
    Protection/BitLocker/CFA status, and 24h critical/error events, then executes age-filtered
    weekly cleanup and hardware-aware SSD TRIM before exporting a formatted HTML report to Desktop.
#>


# Auto-elevate to Administrator if not already running elevated
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -NoExit -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

$ErrorActionPreference = 'Continue'

function Escape-Html {
    param([AllowNull()][string]$Text)
    if ([string]::IsNullOrEmpty($Text)) { return '' }
    return [System.Net.WebUtility]::HtmlEncode($Text)
}

$reportDate = Get-Date -Format 'yyyy-MM-dd HH:mm'
$fileStamp  = Get-Date -Format 'yyyy-MM-dd_HHmm'
$desktopDir = [Environment]::GetFolderPath('Desktop')
$htmlPath   = Join-Path $desktopDir "Weekly_Health_Maintenance_$($env:COMPUTERNAME)_$fileStamp.html"
$htmlBody   = [System.Text.StringBuilder]::new()

Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host " WINDOWS 11 SYSTEM HEALTH & WEEKLY MAINTENANCE " -ForegroundColor Cyan
Write-Host " Computer: $env:COMPUTERNAME " -ForegroundColor Cyan
Write-Host " Date: $reportDate " -ForegroundColor Cyan
Write-Host "=======================================================`n" -ForegroundColor Cyan

# =======================================================================
# PHASE 1: SYSTEM HEALTH & SECURITY AUDIT
# =======================================================================

# 1. OS, Uptime & Pending Reboot Status
Write-Host "[1/8] OS, SYSTEM UPTIME & REBOOT STATUS" -ForegroundColor Yellow
$os = Get-CimInstance Win32_OperatingSystem
$uptime = (Get-Date) - $os.LastBootUpTime
$osText = "$($os.Caption) (Build $($os.BuildNumber))"
$uptimeText = "$($uptime.Days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes"

$updateExeVolatile = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Updates" -Name UpdateExeVolatile -ErrorAction SilentlyContinue).UpdateExeVolatile
$pendingReboot = (
    (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending") -or
    (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired") -or
    ($null -ne $updateExeVolatile -and $updateExeVolatile -ne 0)
)
$rebootBadge = if ($pendingReboot) { 'badge-warn' } else { 'badge-ok' }
$rebootText  = if ($pendingReboot) { 'Reboot Pending' } else { 'Clear' }

Write-Host "OS: $osText"
Write-Host "Uptime: $uptimeText"
Write-Host "Pending Reboot: $rebootText`n" -ForegroundColor $(if ($pendingReboot) { 'Yellow' } else { 'Green' })

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>1. OS, System Uptime &amp; Reboot Status</h2>
  <table>
    <tr><th>Operating System</th><td>$(Escape-Html $osText)</td></tr>
    <tr><th>System Uptime</th><td>$(Escape-Html $uptimeText)</td></tr>
    <tr><th>Last Boot Time</th><td>$(Escape-Html ($os.LastBootUpTime.ToString('yyyy-MM-dd HH:mm:ss')))</td></tr>
    <tr><th>Pending Update Reboot</th><td><span class="badge $rebootBadge">$rebootText</span></td></tr>
  </table>
</section>
"@
)

# 2. CPU & Memory Usage
Write-Host "[2/8] CPU & MEMORY UTILIZATION" -ForegroundColor Yellow
$cpuLoad = [math]::Round(((Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average), 1)
$totalMem = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
$freeMem = [math]::Round($os.FreePhysicalMemory / 1MB, 2)
$usedMem = [math]::Round($totalMem - $freeMem, 2)
$usedMemPercent = [math]::Round((($totalMem - $freeMem) / $totalMem) * 100, 1)

Write-Host "CPU Load: $cpuLoad%"
Write-Host "RAM Used: $usedMem GB / $totalMem GB ($usedMemPercent%)`n"

$cpuBadge = if ($cpuLoad -gt 85) { 'badge-bad' } else { 'badge-ok' }
$ramBadge = if ($usedMemPercent -gt 85) { 'badge-bad' } else { 'badge-ok' }

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>2. CPU &amp; Memory Utilization</h2>
  <table>
    <tr><th>CPU Load</th><td><span class="badge $cpuBadge">$cpuLoad%</span></td></tr>
    <tr><th>Memory Used</th><td><span class="badge $ramBadge">$usedMem GB / $totalMem GB ($usedMemPercent%)</span></td></tr>
  </table>
</section>
"@
)

# 3. Disk Space & Physical Drive Health
Write-Host "[3/8] STORAGE & DRIVE HEALTH" -ForegroundColor Yellow
$diskRows = [System.Text.StringBuilder]::new()

Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
    $sizeGB = [math]::Round($_.Size / 1GB, 1)
    $freeGB = [math]::Round($_.FreeSpace / 1GB, 1)
    $freePct = [math]::Round(($_.FreeSpace / $_.Size) * 100, 1)
    $isLow = $freePct -lt 15
    $color = if ($isLow) { "Red" } else { "Green" }
    $badge = if ($isLow) { "badge-bad" } else { "badge-ok" }
    Write-Host "Drive $($_.DeviceID) - $freeGB GB free of $sizeGB GB ($freePct% free)" -ForegroundColor $color
    [void]$diskRows.AppendLine("<tr><td>Logical Volume $(Escape-Html $_.DeviceID)</td><td>$freeGB GB free of $sizeGB GB</td><td><span class=`"badge $badge`">$freePct% Free</span></td></tr>")
}

Get-PhysicalDisk | ForEach-Object {
    $isHealthy = $_.HealthStatus -eq "Healthy"
    $statusColor = if ($isHealthy) { "Green" } else { "Red" }
    $badge = if ($isHealthy) { "badge-ok" } else { "badge-bad" }
    $rel = $_ | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
    $extra = @()
    if ($rel -and $null -ne $rel.Wear) { $extra += "Wear: $($rel.Wear)%" }
    if ($rel -and $null -ne $rel.Temperature) { $extra += "Temp: $($rel.Temperature)�C" }
    $extraStr = if ($extra.Count -gt 0) { " | " + ($extra -join ", ") } else { "" }

    Write-Host "Physical Disk '$($_.FriendlyName)': $($_.HealthStatus)$extraStr" -ForegroundColor $statusColor
    [void]$diskRows.AppendLine("<tr><td>Physical Disk: $(Escape-Html $_.FriendlyName)</td><td>$(Escape-Html $_.MediaType) ($([math]::Round($_.Size / 1GB, 0)) GB$(Escape-Html $extraStr))</td><td><span class=`"badge $badge`">$(Escape-Html $_.HealthStatus)</span></td></tr>")
}
Write-Host ""

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>3. Storage &amp; Drive Health</h2>
  <table>
    <thead><tr><th>Target</th><th>Capacity / Details</th><th>Status</th></tr></thead>
    <tbody>$($diskRows.ToString())</tbody>
  </table>
</section>
"@
)

# 4. Stopped Automatic Services
Write-Host "[4/8] AUTOMATIC SERVICES CHECK" -ForegroundColor Yellow
$stoppedAuto = @(Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' })
if ($stoppedAuto.Count -gt 0) {
    Write-Host "Warning - The following Automatic services are NOT running:" -ForegroundColor Red
    $stoppedAuto | Select-Object Name, DisplayName, Status | Format-Table -AutoSize
    $svcRows = ($stoppedAuto | ForEach-Object {
        "<tr><td>$(Escape-Html $_.Name)</td><td>$(Escape-Html $_.DisplayName)</td><td><span class=`"badge badge-bad`">$(Escape-Html $_.Status)</span></td></tr>"
    }) -join "`n"
    $svcHtml = "<table><thead><tr><th>Service Name</th><th>Display Name</th><th>Status</th></tr></thead><tbody>$svcRows</tbody></table>"
} else {
    Write-Host "All Automatic services are running normally.`n" -ForegroundColor Green
    $svcHtml = '<p><span class="badge badge-ok">OK</span> All Automatic services are running normally.</p>'
}

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>4. Automatic Services Check</h2>
  $svcHtml
</section>
"@
)

# 5. Network & Internet Connectivity
Write-Host "[5/8] NETWORK CONNECTIVITY" -ForegroundColor Yellow
$pingGoogle = Test-Connection -ComputerName 8.8.8.8 -Count 1 -Quiet
$dnsCheck = try { [System.Net.Dns]::GetHostAddresses("microsoft.com") | Out-Null; $true } catch { $false }

Write-Host "External Ping (8.8.8.8): $(if ($pingGoogle) { 'OK' } else { 'FAILED' })" -ForegroundColor $(if ($pingGoogle) { 'Green' } else { 'Red' })
Write-Host "DNS Resolution: $(if ($dnsCheck) { 'OK' } else { 'FAILED' })`n" -ForegroundColor $(if ($dnsCheck) { 'Green' } else { 'Red' })

$pingBadge = if ($pingGoogle) { 'badge-ok' } else { 'badge-bad' }
$dnsBadge  = if ($dnsCheck)   { 'badge-ok' } else { 'badge-bad' }

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>5. Network Connectivity</h2>
  <table>
    <tr><th>External Ping (8.8.8.8)</th><td><span class="badge $pingBadge">$(if ($pingGoogle) { 'OK' } else { 'FAILED' })</span></td></tr>
    <tr><th>DNS Resolution (microsoft.com)</th><td><span class="badge $dnsBadge">$(if ($dnsCheck) { 'OK' } else { 'FAILED' })</span></td></tr>
  </table>
</section>
"@
)

# 6. VBS, Credential Guard, LSA & Core Platform Security
Write-Host "[6/8] VBS, CREDENTIAL & PLATFORM SECURITY" -ForegroundColor Yellow
$dg     = Get-CimInstance -Namespace root\Microsoft\Windows\DeviceGuard -ClassName Win32_DeviceGuard -ErrorAction SilentlyContinue
$lsa    = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -ErrorAction SilentlyContinue
$cgScen = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\CredentialGuard' -ErrorAction SilentlyContinue).Enabled
$svcRun = if ($dg) { @($dg.SecurityServicesRunning) } else { @() }

$evBoot = @(Get-WinEvent -FilterHashtable @{
    LogName = 'System'; ProviderName = 'Microsoft-Windows-Wininit'; Id = 12, 13; StartTime = $os.LastBootUpTime
} -ErrorAction SilentlyContinue)
$evIds = @($evBoot | ForEach-Object { $_.Id })

$vbsOn  = ($dg -and $dg.VirtualizationBasedSecurityStatus -eq 2)
$hvciOn = (2 -in $svcRun)
$khspOn = (5 -in $svcRun)
$cgOn   = (1 -in $svcRun) -or (($evIds -contains 13) -and [bool](Get-Process -Name 'LsaIso' -ErrorAction SilentlyContinue) -and ($lsa.LsaCfgFlags -in 1, 2 -or $cgScen -eq 1))
$pplOn  = ($evIds -contains 12) -or ($lsa.RunAsPPL -in 1, 2)

$bl     = Get-BitLockerVolume -MountPoint 'C:' -ErrorAction SilentlyContinue
$blOn   = ($bl -and $bl.ProtectionStatus -eq 'On' -and $bl.VolumeStatus -eq 'FullyEncrypted')
$cfaVal = (Get-MpPreference -ErrorAction SilentlyContinue).EnableControlledFolderAccess
$cfaOn  = ($cfaVal -eq 1)

$secItems = @(
    [PSCustomObject]@{ Label = 'VBS Engine';                   Active = $vbsOn;  Detail = if ($vbsOn)  { 'Running (VTL1 Active)' } else { "Off ($($dg.VirtualizationBasedSecurityStatus))" } }
    [PSCustomObject]@{ Label = 'Memory Integrity (HVCI)';      Active = $hvciOn; Detail = if ($hvciOn) { 'Active' } else { 'Off' } }
    [PSCustomObject]@{ Label = 'Kernel Stack Protection';      Active = $khspOn; Detail = if ($khspOn) { 'Active (KHSP)' } else { 'Off' } }
    [PSCustomObject]@{ Label = 'Credential Guard (LsaIso)';    Active = $cgOn;   Detail = if ($cgOn)   { "Active (Wininit 13, LsaCfgFlags=$($lsa.LsaCfgFlags))" } else { 'Off' } }
    [PSCustomObject]@{ Label = 'LSA Protection (RunAsPPL)';    Active = $pplOn;  Detail = if ($pplOn)  { "Active (RunAsPPL=$($lsa.RunAsPPL), Boot=$($lsa.RunAsPPLBoot))" } else { 'Off' } }
    [PSCustomObject]@{ Label = 'BitLocker Encryption (C:)';    Active = $blOn;   Detail = if ($blOn)   { 'Active (100% Encrypted)' } elseif ($bl) { "$($bl.ProtectionStatus) ($($bl.VolumeStatus))" } else { 'Unavailable' } }
    [PSCustomObject]@{ Label = 'Controlled Folder Access';     Active = $cfaOn;  Detail = switch ($cfaVal) { 1 { 'Enabled' } 2 { 'Audit Mode' } default { 'Disabled' } } }
)

$secRows = [System.Text.StringBuilder]::new()
foreach ($item in $secItems) {
    $c = if ($item.Active) { 'Green' } else { 'Red' }
    $b = if ($item.Active) { 'badge-ok' } else { 'badge-bad' }
    Write-Host ("{0,-28}: {1}" -f $item.Label, $item.Detail) -ForegroundColor $c
    [void]$secRows.AppendLine("<tr><th>$(Escape-Html $item.Label)</th><td><span class=`"badge $b`">$(Escape-Html $item.Detail)</span></td></tr>")
}
Write-Host ""

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>6. VBS, Credential &amp; Platform Security</h2>
  <table>
    $($secRows.ToString())
  </table>
</section>
"@
)

# 7. Recent System Errors (Last 24 Hours - Read-Only, Preserves Logs)
Write-Host "[7/8] CRITICAL & ERROR EVENTS (LAST 24 HOURS)" -ForegroundColor Yellow
$startTime = (Get-Date).AddHours(-24)
$errors = @(Get-WinEvent -FilterHashtable @{LogName='System'; Level=1,2; StartTime=$startTime} -ErrorAction SilentlyContinue)

if ($errors.Count -gt 0) {
    Write-Host "Found $($errors.Count) Critical/Error events in System log (showing latest 5):" -ForegroundColor Red
    $errors | Select-Object -First 5 TimeCreated, Id, ProviderName, Message | Format-Table -Wrap
    $errRows = ($errors | Select-Object -First 10 | ForEach-Object {
        $msg = ($_.Message -replace '\r?\n', ' ').Trim()
        "<tr><td>$(Escape-Html ($_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss')))</td><td>$($_.Id)</td><td>$(Escape-Html $_.ProviderName)</td><td>$(Escape-Html $msg)</td></tr>"
    }) -join "`n"
    $errHtml = "<p><span class=`"badge badge-bad`">Warning</span> Found $($errors.Count) Critical/Error events (showing up to latest 10):</p><table><thead><tr><th>Time</th><th>Event ID</th><th>Source</th><th>Message</th></tr></thead><tbody>$errRows</tbody></table>"
} else {
    Write-Host "No Critical or Error events found in the System log over the last 24 hours.`n" -ForegroundColor Green
    $errHtml = '<p><span class="badge badge-ok">OK</span> No Critical or Error events found in the System log over the last 24 hours.</p>'
}

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>7. Critical &amp; Error Events (Last 24 Hours)</h2>
  $errHtml
</section>
"@
)

# =======================================================================
# PHASE 2: SAFE WEEKLY CLEANUP & SSD OPTIMIZATION
# =======================================================================
Write-Host "[8/8] WEEKLY CLEANUP & OPTIMIZATION" -ForegroundColor Yellow
$maintRows = [System.Text.StringBuilder]::new()
$freeBeforeBytes = (Get-PSDrive -Name C).Free

function Add-MaintRow {
    param([string]$Task, [string]$Detail, [ValidateSet('OK','Skipped','Failed')][string]$State)
    $badgeClass = switch ($State) {
        'OK'      { 'badge-ok' }
        'Skipped' { 'badge-warn' }
        'Failed'  { 'badge-bad' }
    }
    $consoleColor = switch ($State) {
        'OK'      { 'Green' }
        'Skipped' { 'Yellow' }
        'Failed'  { 'Red' }
    }
    Write-Host (" [{0}] {1}: {2}" -f $State.ToUpper(), $Task, $Detail) -ForegroundColor $consoleColor
    [void]$maintRows.AppendLine("<tr><td>$(Escape-Html $Task)</td><td>$(Escape-Html $Detail)</td><td><span class=`"badge $badgeClass`">$State</span></td></tr>")
}

# 8a. Age-Filtered Temp Folders (> 7 days)
try {
    $tempCutoff = (Get-Date).AddDays(-7)
    $tempFolders = @($env:TEMP, "$env:SystemRoot\Temp", "$env:LocalAppData\Temp") | Select-Object -Unique
    $tempCount = 0
    foreach ($folder in $tempFolders) {
        if (Test-Path -Path $folder) {
            $oldFiles = @(Get-ChildItem -Path $folder -Recurse -File -Force -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $tempCutoff })
            $tempCount += $oldFiles.Count
            $oldFiles | Remove-Item -Force -ErrorAction SilentlyContinue
            Get-ChildItem -Path $folder -Recurse -Directory -Force -ErrorAction SilentlyContinue |
                Sort-Object { $_.FullName.Length } -Descending |
                Where-Object { @(Get-ChildItem -Path $_.FullName -Force -ErrorAction SilentlyContinue).Count -eq 0 } |
                Remove-Item -Force -ErrorAction SilentlyContinue
        }
    }
    Add-MaintRow -Task "Temp Directories (> 7 days)" -Detail "Removed $tempCount stale temp file(s)" -State "OK"
} catch {
    Add-MaintRow -Task "Temp Directories (> 7 days)" -Detail "$_" -State "Failed"
}

# 8b. Age-Filtered Windows Update Downloads (> 14 days, Reboot-Safe)
$runningWU = @()
try {
    if ($pendingReboot) {
        Add-MaintRow -Task "Windows Update Downloads (> 14 days)" -Detail "Skipped due to pending system reboot" -State "Skipped"
    } else {
        $downloadPath = "$env:SystemRoot\SoftwareDistribution\Download"
        $wuCutoff = (Get-Date).AddDays(-14)
        $staleWU = @(Get-ChildItem -Path $downloadPath -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $wuCutoff })
        if ($staleWU.Count -gt 0) {
            $runningWU = @(Get-Service -Name wuauserv, bits -ErrorAction SilentlyContinue | Where-Object { $_.Status -eq 'Running' })
            foreach ($svc in $runningWU) { Stop-Service -Name $svc.Name -Force -ErrorAction SilentlyContinue }
            $staleWU | Remove-Item -Force -ErrorAction SilentlyContinue
            Get-ChildItem -Path $downloadPath -Recurse -Directory -ErrorAction SilentlyContinue |
                Sort-Object { $_.FullName.Length } -Descending |
                Where-Object { @(Get-ChildItem -Path $_.FullName -Force -ErrorAction SilentlyContinue).Count -eq 0 } |
                Remove-Item -Force -ErrorAction SilentlyContinue
            foreach ($svc in $runningWU) { Start-Service -Name $svc.Name -ErrorAction SilentlyContinue }
            Add-MaintRow -Task "Windows Update Downloads (> 14 days)" -Detail "Pruned $($staleWU.Count) stale payload(s); DataStore preserved" -State "OK"
        } else {
            Add-MaintRow -Task "Windows Update Downloads (> 14 days)" -Detail "No stale download files older than 14 days" -State "OK"
        }
    }
} catch {
    foreach ($svc in $runningWU) { Start-Service -Name $svc.Name -ErrorAction SilentlyContinue }
    Add-MaintRow -Task "Windows Update Downloads (> 14 days)" -Detail "$_" -State "Failed"
}

# 8c. Delivery Optimization Cache (Native API)
try {
    if (Get-Command Delete-DeliveryOptimizationCache -ErrorAction SilentlyContinue) {
        Delete-DeliveryOptimizationCache -Force -ErrorAction SilentlyContinue | Out-Null
        Add-MaintRow -Task "Delivery Optimization Cache" -Detail "Cleared peer update cache via native cmdlet" -State "OK"
    } else {
        Add-MaintRow -Task "Delivery Optimization Cache" -Detail "Cmdlet unavailable on this edition" -State "Skipped"
    }
} catch {
    Add-MaintRow -Task "Delivery Optimization Cache" -Detail "$_" -State "Failed"
}

# 8d. Package Manager Caches (UniGetUI & Winget)
try {
    $uniGetCache = "$env:LocalAppData\UniGetUI"
    if (Test-Path $uniGetCache) {
        Remove-Item -Path "$uniGetCache\*.log" -Force -ErrorAction SilentlyContinue
        Remove-Item -Path "$uniGetCache\CachedData\*" -Recurse -Force -ErrorAction SilentlyContinue
    }
    $wingetCache = "$env:LocalAppData\Packages\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\LocalState\cache"
    if (Test-Path $wingetCache) {
        Remove-Item -Path "$wingetCache\*" -Recurse -Force -ErrorAction SilentlyContinue
    }
    Add-MaintRow -Task "Package Manager Caches" -Detail "Cleared UniGetUI and Winget caches" -State "OK"
} catch {
    Add-MaintRow -Task "Package Manager Caches" -Detail "$_" -State "Failed"
}

# 8e. Age-Filtered Windows Error Reports & Minidumps (> 14 days)
try {
    $dumpCutoff = (Get-Date).AddDays(-14)
    $oldReports = @(
        Get-ChildItem -Path "$env:ProgramData\Microsoft\Windows\WER\ReportArchive", "$env:ProgramData\Microsoft\Windows\WER\ReportQueue", "$env:SystemRoot\Minidump" -Recurse -ErrorAction SilentlyContinue |
        Where-Object { $_.LastWriteTime -lt $dumpCutoff }
    )
    $oldReports | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
    Add-MaintRow -Task "Error Reports & Minidumps (> 14 days)" -Detail "Pruned $($oldReports.Count) archived report/dump item(s)" -State "OK"
} catch {
    Add-MaintRow -Task "Error Reports & Minidumps (> 14 days)" -Detail "$_" -State "Failed"
}

# 8f. Recycle Bin & DNS/ARP Network Cache Refresh
try {
    Clear-RecycleBin -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
    Clear-DnsClientCache -ErrorAction SilentlyContinue
    netsh interface ip delete arpcache | Out-Null
    Add-MaintRow -Task "Recycle Bin & Network Caches" -Detail "Emptied Recycle Bin; flushed DNS & ARP caches" -State "OK"
} catch {
    Add-MaintRow -Task "Recycle Bin & Network Caches" -Detail "$_" -State "Failed"
}

# 8g. Hardware-Aware Drive Optimization (TRIM-Only on SSDs, Defrag on HDDs)
try {
    $optSummary = @()
    Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter } | ForEach-Object {
        $letter = $_.DriveLetter
        $part = Get-Partition -DriveLetter $letter -ErrorAction SilentlyContinue
        $physDisk = if ($part) { Get-PhysicalDisk -DeviceNumber $part.DiskNumber -ErrorAction SilentlyContinue } else { $null }
        if ($physDisk -and $physDisk.MediaType -eq 'HDD') {
            Optimize-Volume -DriveLetter $letter -Defrag -Verbose:$false -ErrorAction SilentlyContinue
            $optSummary += "${letter}: (Defrag)"
        } else {
            Optimize-Volume -DriveLetter $letter -ReTrim -Verbose:$false -ErrorAction SilentlyContinue
            $optSummary += "${letter}: (TRIM)"
        }
    }
    Add-MaintRow -Task "Fixed Drive Optimization" -Detail ($optSummary -join ", ") -State "OK"
} catch {
    Add-MaintRow -Task "Fixed Drive Optimization" -Detail "$_" -State "Failed"
}

# 8h. Windows Defender Signature Update & Status
$ps = $null
try {
    $ps = [PowerShell]::Create().AddCommand('Update-MpSignature').AddParameter('ErrorAction', 'SilentlyContinue')
    $handle = $ps.BeginInvoke()

    $spinner = @('|', '/', '-', '\')
    $idx = 0
    $sw = [System.Diagnostics.Stopwatch]::StartNew()

    while (-not $handle.IsCompleted) {
        $elapsed = [math]::Floor($sw.Elapsed.TotalSeconds)
        Write-Host ("`r [{0}] Updating Windows Defender signatures... ({1}s) " -f $spinner[$idx % 4], $elapsed) -NoNewline -ForegroundColor Gray
        Start-Sleep -Milliseconds 200
        $idx++
    }

    $sw.Stop()
    $null = $ps.EndInvoke($handle)

    # Clear the spinner line cleanly before printing the final status row
    Write-Host ("`r" + (" " * 68) + "`r") -NoNewline

    $duration = [math]::Round($sw.Elapsed.TotalSeconds, 1)
    $defender = Get-MpComputerStatus -ErrorAction Stop
    Add-MaintRow -Task "Windows Defender Signatures" -Detail "Updated in ${duration}s (Signature Age: $($defender.AntivirusSignatureAge)d | Last Quick Scan: $($defender.QuickScanAge)d ago)" -State "OK"
} catch {
    Write-Host ("`r" + (" " * 68) + "`r") -NoNewline
    Add-MaintRow -Task "Windows Defender Signatures" -Detail "Could not update or query Defender status: $_" -State "Failed"
} finally {
    if ($null -ne $ps) { $ps.Dispose() }
}

$freeAfterBytes = (Get-PSDrive -Name C).Free
$reclaimedMB = [math]::Round([math]::Max(0, ($freeAfterBytes - $freeBeforeBytes)) / 1MB, 2)
$currentFreeGB = [math]::Round($freeAfterBytes / 1GB, 2)
Add-MaintRow -Task "Net Space Reclaimed (C:)" -Detail "$reclaimedMB MB freed (Current Free: $currentFreeGB GB)" -State "OK"
Write-Host ""

[void]$htmlBody.AppendLine(@"
<section class="card">
  <h2>8. Weekly Cleanup &amp; Optimization</h2>
  <table>
    <thead><tr><th>Task</th><th>Result / Details</th><th>Status</th></tr></thead>
    <tbody>$($maintRows.ToString())</tbody>
  </table>
</section>
"@
)

# =======================================================================
# BUILD AND SAVE HTML REPORT
# =======================================================================
$fullHtml = @"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Windows Weekly Health &amp; Maintenance Report - $(Escape-Html $env:COMPUTERNAME)</title>
<style>
  body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #0f172a; color: #e2e8f0; margin: 0; padding: 24px; }
  .container { max-width: 980px; margin: 0 auto; }
  header { background: #1e293b; border: 1px solid #334155; border-left: 5px solid #38bdf8; border-radius: 8px; padding: 20px 24px; margin-bottom: 20px; }
  header h1 { margin: 0 0 8px 0; font-size: 22px; color: #f8fafc; letter-spacing: 0.4px; }
  header .meta { font-size: 13px; color: #94a3b8; }
  .card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 18px 22px; margin-bottom: 16px; }
  .card h2 { margin: 0 0 12px 0; font-size: 16px; color: #38bdf8; border-bottom: 1px solid #334155; padding-bottom: 8px; }
  table { width: 100%; border-collapse: collapse; font-size: 14px; }
  th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid #293548; vertical-align: top; }
  th { color: #94a3b8; font-weight: 600; width: 28%; }
  thead th { width: auto; color: #cbd5e1; background: #162032; }
  tr:last-child td, tr:last-child th { border-bottom: none; }
  .badge { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: 12px; font-weight: 600; }
  .badge-ok { background: rgba(34, 197, 94, 0.16); color: #4ade80; border: 1px solid rgba(74, 222, 128, 0.35); }
  .badge-warn { background: rgba(234, 179, 8, 0.16); color: #facc15; border: 1px solid rgba(250, 204, 21, 0.35); }
  .badge-bad { background: rgba(239, 68, 68, 0.16); color: #f87171; border: 1px solid rgba(248, 113, 113, 0.35); }
  footer { text-align: center; font-size: 12px; color: #64748b; margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
  <header>
    <h1>Windows Weekly Health &amp; Maintenance Report</h1>
    <div class="meta">Computer: <strong>$(Escape-Html $env:COMPUTERNAME)</strong> &nbsp;|&nbsp; Generated: <strong>$(Escape-Html $reportDate)</strong></div>
  </header>
  $($htmlBody.ToString())
  <footer>Generated by PowerShell System Health &amp; Weekly Maintenance</footer>
</div>
</body>
</html>
"@


Set-Content -Path $htmlPath -Value $fullHtml -Encoding UTF8

Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host " HEALTH CHECK & MAINTENANCE COMPLETE " -ForegroundColor Cyan
Write-Host " HTML Report Saved To Desktop: " -ForegroundColor Cyan
Write-Host " $htmlPath" -ForegroundColor Green
Write-Host "=======================================================" -ForegroundColor Cyan