Invoke-Win11SecurityAuditAndRepair.ps1

<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID 3eeebd41-5696-41bf-8337-2f9956ec15ea
 
.AUTHOR waresoft
 
.COMPANYNAME waresoft
 
.COPYRIGHT (c) 2026 waresoft. All rights reserved.
 
.TAGS powershell windows-11 security-audit system-repair windows-update bitlocker controlled-folder-access unquoted-service-paths smart-health html-report self-elevating
 
.LICENSEURI https://opensource.org/licenses/MIT
 
.RELEASENOTES
Key Features
Phase 1: Security & System Health Audit
BitLocker Encryption Check: Inspects drive C: encryption status and percentage via Get-BitLockerVolume.
 
Controlled Folder Access Audit: Checks Windows Defender ransomware protection mode (Enabled, Audit Mode, or Disabled) via Get-MpPreference.
 
Drive SMART Health Check: Evaluates physical disk health (Healthy vs. non-healthy states) across attached storage via Get-PhysicalDisk.
 
Unquoted Service Path Scan: Queries Win32_Service via Get-CimInstance to flag third-party service paths containing spaces without enclosing quotes.
 
24-Hour Critical Event Harvest: Captures recent System and Application events (Levels 1–3, up to 15 entries) before repair steps clear system logs.
 
Phase 2: System Repair & Recovery
Windows Update Reset: Stops wuauserv, bits, cryptsvc, and appidsvc, purges prior .bak/.old cache backups, renames SoftwareDistribution and catroot2 to .bak, and restarts the services.
 
Temp, Recycle Bin & Network Reset: Clears user/system/local temp directories, empties the Recycle Bin, flushes DNS client cache, clears the ARP cache, and reloads NetBIOS name tables.
 
Delivery Optimization & Package Caches: Clears Delivery Optimization cache (cycling dosvc) and purges caches for UniGetUI, winget, choco, npm, and pip when present.
 
Crash Dumps, Prefetch & UI Caches: Purges minidumps, MEMORY.DMP, Windows Error Reporting files, CBS logs, Prefetch files, and resets Font, thumbnail, and icon caches (cycling FontCache).
 
Event Logs, Windows.old & Shadow Copies: Flushes populated event logs via wevtutil.exe, removes lingering Windows.old folders if present, and deletes the oldest volume shadow copy on C: via vssadmin.
 
Drive Optimization & Defender Update: Runs TRIM/defrag optimization across fixed drives (Optimize-Volume) and updates Windows Defender signatures while reporting real-time protection, signature age, and last quick scan age.
 
#>


# =======================================================================

# SCRIPT: Invoke-Win11SecurityAuditAndRepair.ps1

# TITLE: Windows 11 Security Audit & System Repair

# =======================================================================

# AUTO-ELEVATION BLOCK (Self-Elevate to Administrator)

# =======================================================================

<#
.DESCRIPTION
    An automated PowerShell utility for Windows 11 that self-elevates to Administrator and runs a two-phase security/health audit followed by a system repair and cache-reset routine, outputting a dark-themed HTML report to the Desktop and opening it automatically upon completion.
#>


$CurrentUser = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$IsAdmin = $CurrentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $IsAdmin) {
    if ($PSCommandPath) {
        Write-Host "Requesting Administrator privileges..." -ForegroundColor Yellow
        $Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`""
        Start-Process -FilePath "powershell.exe" -ArgumentList $Arguments -Verb RunAs
        Exit
    } else {
        Write-Warning "Administrator privileges are required. Please run PowerShell as Administrator."
        Exit
    }
}

# Ensure script continues on minor non-terminating errors
$ErrorActionPreference = "Continue"

# =======================================================================
# HTML REPORT INITIALIZATION
# =======================================================================
$ReportDate = Get-Date -Format 'yyyy-MM-dd HH:mm'
$ReportPath = "$env:USERPROFILE\Desktop\Win11_Security_Audit_Repair_$(Get-Date -Format 'yyyyMMdd_HHmm').html"

$HtmlHead = @"
<meta charset="utf-8">
<style>
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #121212; color: #e0e0e0; margin: 40px; }
    h1 { color: #00bcd4; border-bottom: 2px solid #333; padding-bottom: 10px; }
    h2 { color: #4caf50; margin-top: 30px; }
    table { border-collapse: collapse; width: 100%; margin-bottom: 20px; background-color: #1e1e1e; }
    th, td { border: 1px solid #333; padding: 10px; text-align: left; }
    th { background-color: #2c2c2c; color: #00bcd4; }
    .status-ok { color: #4caf50; font-weight: bold; }
    .status-warn { color: #ffeb3b; font-weight: bold; }
    .status-fail { color: #f44336; font-weight: bold; }
    .repair-log { background-color: #1e1e1e; padding: 15px; border-left: 4px solid #00bcd4; font-family: monospace; white-space: pre-wrap; }
</style>
"@


$HtmlBody = "<h1>Windows 11 Security Audit &amp; System Repair Report</h1>"
$HtmlBody += "<p><strong>Scan Date:</strong> $ReportDate</p>"
$HtmlBody += "<p><strong>Computer:</strong> $env:COMPUTERNAME</p>"

Write-Host "=======================================================================" -ForegroundColor Cyan
Write-Host " WINDOWS 11 SECURITY AUDIT & SYSTEM REPAIR ROUTINE " -ForegroundColor Cyan
Write-Host "=======================================================================" -ForegroundColor Cyan
Write-Host ""

# =======================================================================
# PHASE 1: SECURITY & SYSTEM HEALTH AUDIT
# =======================================================================
Write-Host ">>> STARTING PHASE 1: SECURITY & SYSTEM HEALTH AUDIT <<<" -ForegroundColor Magenta

# 1. BitLocker Status
Write-Host "[*] Auditing BitLocker Encryption..." -ForegroundColor Gray
$HtmlBody += "<h2>Security: BitLocker Status</h2>"
try {
    $BL = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop
    $Status = if ($BL.VolumeStatus -eq 'FullyEncrypted') { "<span class='status-ok'>Fully Encrypted</span>" } else { "<span class='status-warn'>$($BL.VolumeStatus)</span>" }
    $HtmlBody += "<table><tr><th>Drive</th><th>Protection Status</th><th>Encryption Percentage</th></tr><tr><td>$($BL.MountPoint)</td><td>$Status</td><td>$($BL.EncryptionPercentage)%</td></tr></table>"
} catch {
    $HtmlBody += "<p class='status-warn'>BitLocker module unavailable or drive C: not managed.</p>"
}

# 2. Controlled Folder Access
Write-Host "[*] Auditing Controlled Folder Access..." -ForegroundColor Gray
$HtmlBody += "<h2>Security: Controlled Folder Access</h2>"
$CFA = (Get-MpPreference).EnableControlledFolderAccess
$CFAStatus = switch ($CFA) {
    1 { "<span class='status-ok'>Enabled</span>" }
    2 { "<span class='status-warn'>Audit Mode</span>" }
    default { "<span class='status-fail'>Disabled</span>" }
}
$HtmlBody += "<table><tr><th>Feature</th><th>Status</th></tr><tr><td>Controlled Folder Access (Ransomware Protection)</td><td>$CFAStatus</td></tr></table>"

# 3. Drive SMART Health
Write-Host "[*] Checking Drive SMART Health..." -ForegroundColor Gray
$HtmlBody += "<h2>Hardware: Drive Health (SMART)</h2>"
$Drives = Get-PhysicalDisk | Select-Object DeviceId, Model, MediaType, HealthStatus
$DriveHtml = "<table><tr><th>Drive ID</th><th>Model</th><th>Type</th><th>Health Status</th></tr>"
foreach ($Drive in $Drives) {
    $HealthClass = if ($Drive.HealthStatus -eq 'Healthy') { "status-ok" } else { "status-fail" }
    $DriveHtml += "<tr><td>$($Drive.DeviceId)</td><td>$($Drive.Model)</td><td>$($Drive.MediaType)</td><td class='$HealthClass'>$($Drive.HealthStatus)</td></tr>"
}
$DriveHtml += "</table>"
$HtmlBody += $DriveHtml

# 4. Unquoted Service Path Vulnerability Scan
Write-Host "[*] Scanning for Unquoted Service Paths..." -ForegroundColor Gray
$HtmlBody += "<h2>Security: Unquoted Service Paths (LPE Risk)</h2>"
$UnquotedServices = Get-CimInstance Win32_Service | Where-Object {
    $_.PathName -and
    $_.PathName -notmatch '^"' -and
    $_.PathName -match ' ' -and
    $_.PathName -notmatch '(?i)^C:\\Windows\\'
}
if (-not $UnquotedServices) {
    $HtmlBody += "<p class='status-ok'>No vulnerable unquoted service paths detected.</p>"
} else {
    $HtmlBody += "<table><tr><th>Service Name</th><th>Display Name</th><th>Vulnerable Path</th></tr>"
    foreach ($Svc in $UnquotedServices) {
        $EncodedPath = [System.Net.WebUtility]::HtmlEncode($Svc.PathName)
        $EncodedName = [System.Net.WebUtility]::HtmlEncode($Svc.DisplayName)
        $HtmlBody += "<tr><td>$($Svc.Name)</td><td>$EncodedName</td><td class='status-fail'>$EncodedPath</td></tr>"
    }
    $HtmlBody += "</table>"
}

# 5. Critical Event Logs (Harvested BEFORE repair actions clear logs)
Write-Host "[*] Harvesting Recent Critical Event Logs..." -ForegroundColor Gray
$HtmlBody += "<h2>System Health: Recent Critical Errors (Last 24h)</h2>"
try {
    $Events = Get-WinEvent -FilterHashtable @{LogName='System','Application'; Level=1,2,3; StartTime=(Get-Date).AddDays(-1)} -MaxEvents 15 -ErrorAction Stop
    $HtmlBody += "<table><tr><th>Time</th><th>Log</th><th>Source</th><th>Event ID</th><th>Message</th></tr>"
    foreach ($Evt in $Events) {
        $CleanMsg = ($Evt.Message -replace "`n"," " -replace "`r","")
        $EncodedMsg = [System.Net.WebUtility]::HtmlEncode($CleanMsg)
        $HtmlBody += "<tr><td>$($Evt.TimeCreated)</td><td>$($Evt.LogName)</td><td>$($Evt.ProviderName)</td><td>$($Evt.Id)</td><td>$EncodedMsg</td></tr>"
    }
    $HtmlBody += "</table>"
} catch {
    $HtmlBody += "<p class='status-ok'>No critical errors or warnings found in the last 24 hours.</p>"
}

Write-Host ""
Write-Host ">>> STARTING PHASE 2: SYSTEM REPAIR & RECOVERY <<<" -ForegroundColor Magenta
$HtmlBody += "<h2>Repair: Execution Log</h2><div class='repair-log'>"

# Wrapper function to log to both Console and HTML safely
function Log-Action ($Message, $Color) {
    Write-Host $Message -ForegroundColor $Color
    $script:HtmlBody += ([System.Net.WebUtility]::HtmlEncode($Message) + "`n")
}

# --- REPAIR ROUTINES BEGIN ---

Log-Action "[1/12] Safely resetting Windows Update Cache..." "Yellow"
try {
    Stop-Service -Name wuauserv, bits, cryptsvc, appidsvc -Force -ErrorAction SilentlyContinue

    $legacyBackups = @(
        "$env:SystemRoot\SoftwareDistribution.bak",
        "$env:SystemRoot\SoftwareDistribution.old",
        "$env:SystemRoot\System32\catroot2.bak",
        "$env:SystemRoot\System32\catroot2.old"
    )

    foreach ($backup in $legacyBackups) {
        if (Test-Path -Path $backup) {
            Remove-Item -Path $backup -Recurse -Force -ErrorAction SilentlyContinue
        }
    }

    Rename-Item -Path "$env:SystemRoot\SoftwareDistribution" -NewName "SoftwareDistribution.bak" -Force -ErrorAction SilentlyContinue
    Rename-Item -Path "$env:SystemRoot\System32\catroot2" -NewName "catroot2.bak" -Force -ErrorAction SilentlyContinue

    Start-Service -Name wuauserv, bits, cryptsvc, appidsvc -ErrorAction SilentlyContinue

    Log-Action "[+] Windows Update cache cleanly reset." "Green"
} catch {
    Log-Action "[!] Windows Update cache reset encountered an issue: $_" "Red"
}

Log-Action "`n[2/12] Cleaning Temp Directories, Recycle Bin & Resetting Network Stack..." "Yellow"
try {
    $TempFolders = @($env:TEMP, "$env:SystemRoot\Temp", "$env:LocalAppData\Temp")
    foreach ($Folder in $TempFolders) {
        if (Test-Path -Path $Folder) {
            Get-ChildItem -Path $Folder -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
        }
    }
    Clear-DnsClientCache -ErrorAction SilentlyContinue
    netsh interface ip delete arpcache | Out-Null
    nbtstat -R | Out-Null
    Clear-RecycleBin -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
    Log-Action "[+] Temp files, Recycle Bin, and network caches cleared." "Green"
} catch { Log-Action "[!] General repair encountered an issue: $_" "Red" }

Log-Action "`n[3/12] Clearing Delivery Optimization Cache..." "Yellow"
try {
    Stop-Service -Name dosvc -Force -ErrorAction SilentlyContinue
    $DOCache = "$env:SystemRoot\ServiceProfiles\NetworkService\AppData\Local\Microsoft\Windows\DeliveryOptimization\Cache\*"
    if (Test-Path $DOCache) { Remove-Item -Path $DOCache -Recurse -Force -ErrorAction SilentlyContinue }
    Start-Service -Name dosvc -ErrorAction SilentlyContinue
    Log-Action "[+] Delivery Optimization cache cleared." "Green"
} catch { Log-Action "[!] Delivery Optimization cache repair encountered an issue: $_" "Red" }

Log-Action "`n[4/12] Purging Package Manager Caches..." "Yellow"
try {
    $UniGetUICache = "$env:LocalAppData\UniGetUI"
    if (Test-Path $UniGetUICache) {
        Remove-Item -Path "$UniGetUICache\*.log" -Force -ErrorAction SilentlyContinue
        Remove-Item -Path "$UniGetUICache\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 }

    if (Get-Command choco -ErrorAction SilentlyContinue) { choco cache remove --limit-output | Out-Null }
    if (Get-Command npm -ErrorAction SilentlyContinue) { npm cache clean --force --silent | Out-Null }
    if (Get-Command pip -ErrorAction SilentlyContinue) { pip cache purge | Out-Null }

    Log-Action "[+] Package manager caches purged." "Green"
} catch { Log-Action "[!] Package manager cache repair encountered an issue: $_" "Red" }

Log-Action "`n[5/12] Purging Memory Dumps & Windows Error Reports..." "Yellow"
try {
    @("$env:SystemRoot\Minidump\*", "$env:SystemRoot\MEMORY.DMP", "$env:ProgramData\Microsoft\Windows\WER\*", "$env:SystemRoot\Logs\CBS\*.log") | ForEach-Object {
        if (Test-Path $_) { Remove-Item -Path $_ -Recurse -Force -ErrorAction SilentlyContinue }
    }
    Log-Action "[+] Crash dumps and error reports purged." "Green"
} catch { Log-Action "[!] Crash dump purge encountered an issue: $_" "Red" }

Log-Action "`n[6/12] Purging Windows Prefetch Cache..." "Yellow"
try {
    if (Test-Path "$env:SystemRoot\Prefetch\*") { Remove-Item -Path "$env:SystemRoot\Prefetch\*" -Recurse -Force -ErrorAction SilentlyContinue }
    Log-Action "[+] Prefetch cache purged." "Green"
} catch { Log-Action "[!] Prefetch repair encountered an issue: $_" "Red" }

Log-Action "`n[7/12] Resetting Font, Icon, and Thumbnail Caches..." "Yellow"
try {
    Stop-Service -Name FontCache -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:WinDir\ServiceProfiles\LocalService\AppData\Local\FontCache\*" -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:LocalAppData\GDIPFONTCACHEV1.DAT" -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:LocalAppData\Microsoft\Windows\Explorer\thumbcache_*.db" -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:LocalAppData\Microsoft\Windows\Explorer\iconcache_*.db" -Force -ErrorAction SilentlyContinue
    Start-Service -Name FontCache -ErrorAction SilentlyContinue
    Log-Action "[+] Font, Icon, and Thumbnail caches reset." "Green"
} catch { Log-Action "[!] Cache reset encountered an issue: $_" "Red" }

Log-Action "`n[8/12] Flushing Windows Event Viewer Logs..." "Yellow"
try {
    Get-WinEvent -ListLog * -ErrorAction SilentlyContinue | Where-Object { $_.RecordCount -gt 0 } | ForEach-Object { wevtutil.exe cl "$($_.LogName)" 2>$null }
    Log-Action "[+] Event logs flushed." "Green"
} catch { Log-Action "[!] Event log repair encountered an issue: $_" "Red" }

Log-Action "`n[9/12] Checking for lingering Windows.old installations..." "Yellow"
try {
    if (Test-Path "$env:SystemDrive\Windows.old") {
        cmd.exe /c "rd /s /q %systemdrive%\Windows.old" | Out-Null
        Log-Action "[+] Previous Windows installation files removed." "Green"
    } else { Log-Action "[+] No Windows.old folder found. Skipping." "Green" }
} catch { Log-Action "[!] Windows.old removal encountered an issue: $_" "Red" }

Log-Action "`n[10/12] Purging Old Volume Shadow Copies..." "Yellow"
try {
    vssadmin delete shadows /for=C: /oldest /quiet | Out-Null
    Log-Action "[+] Oldest volume shadow copies cleared." "Green"
} catch { Log-Action "[!] Shadow copy repair encountered an issue: $_" "Red" }

Log-Action "`n[11/12] Optimizing All Fixed Drives (TRIM / Defrag)..." "Yellow"
try {
    Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter } | ForEach-Object {
        Log-Action " Optimizing Drive $($_.DriveLetter):..." "Gray"
        Optimize-Volume -DriveLetter $_.DriveLetter -ReTrim -Defrag -Verbose:$false -ErrorAction SilentlyContinue
    }
    Log-Action "[+] All fixed drives optimized successfully." "Green"
} catch { Log-Action "[!] Drive optimization encountered an issue: $_" "Red" }

Log-Action "`n[12/12] Updating Defender & Checking Status:" "Yellow"
$HtmlBody += "</div><h2>Security: Windows Defender Status</h2>"
try {
    Update-MpSignature -ErrorAction SilentlyContinue
    $Defender = Get-MpComputerStatus -ErrorAction Stop
    $DefRTP = if ($Defender.RealTimeProtectionEnabled) { "<span class='status-ok'>Active</span>" } else { "<span class='status-fail'>Disabled</span>" }

    $HtmlBody += "<table><tr><th>Real-Time Protection</th><th>Signature Age</th><th>Last Quick Scan</th></tr>"
    $HtmlBody += "<tr><td>$DefRTP</td><td>$($Defender.AntivirusSignatureAge) days old</td><td>$($Defender.QuickScanAge) days ago</td></tr></table>"
    Log-Action "[+] Defender signatures updated." "Green"
} catch {
    Log-Action "[!] Could not update or query Defender status." "Red"
    $HtmlBody += "<p class='status-fail'>Failed to retrieve Defender status.</p>"
}

# =======================================================================
# REPORT GENERATION & WRAP UP
# =======================================================================
Write-Host "`nGenerating Windows 11 Security Audit & System Repair Report..." -ForegroundColor Cyan
$HtmlFinal = "<html><head>$HtmlHead</head><body>$HtmlBody</body></html>"
$HtmlFinal | Out-File -FilePath $ReportPath -Encoding utf8
Invoke-Item $ReportPath

Write-Host "=======================================================================" -ForegroundColor Cyan
Write-Host " AUDIT & SYSTEM REPAIR ROUTINE COMPLETE " -ForegroundColor Cyan
Write-Host "=======================================================================" -ForegroundColor Cyan

# PAUSE UNTIL USER PRESSES A KEY OR ENTER
Write-Host "`nPress Enter or any key to close this window..." -ForegroundColor Yellow
try {
    if ($Host.UI.RawUI.KeyAvailable) {
        $null = $Host.UI.RawUI.FlushInputBuffer()
    }
    $null = [System.Console]::ReadKey($true)
} catch {
    Read-Host
}