Detect-WindowsUpdateHealth.ps1

<#PSScriptInfo
.VERSION 1.0
.GUID 91d7c3f2-6b4e-4e1a-8f22-3c7b9a1e5d11
.AUTHOR Mert Efe Kanlikilic
.DESCRIPTION A detection script that assesses Windows Update health, identifying stalled updates or misconfigured update components.
#>



$unhealthy = $false

Write-Output "Starting detection"

$wua = Get-Service wuauserv
if ($wua.StartType -ne "Automatic" -or $wua.Status -ne "Running") {
    Write-Output "wuauserv unhealthy"
    $unhealthy = $true
}

$bits = Get-Service BITS
if ($bits.StartType -eq "Disabled") {
    Write-Output "BITS disabled"
    $unhealthy = $true
}

$uso = Get-Service UsoSvc
if ($uso.StartType -eq "Disabled") {
    Write-Output "UsoSvc disabled"
    $unhealthy = $true
}

try {
    $session = New-Object -ComObject Microsoft.Update.Session
    $searcher = $session.CreateUpdateSearcher()
    $history = $searcher.QueryHistory(0,50)

    $lastSuccess = $history |
    Where-Object { $_.ResultCode -eq 2 } |
    Sort-Object Date -Descending |
    Select-Object -First 1

    if ($lastSuccess) {
        $days = (New-TimeSpan -Start $lastSuccess.Date -End (Get-Date)).Days

        Write-Output "Last successful update: $days days ago"

        if ($days -gt 30) {
            $unhealthy = $true
        }
    }
    else {
        Write-Output "No update history found"
        $unhealthy = $true
    }
}
catch {
    Write-Output "WU history check failed"
    $unhealthy = $true
}

if ($unhealthy) {
    Write-Output "Device is UNHEALTHY"
    exit 1
}
else {
    Write-Output "Device is HEALTHY"
    exit 0
}