Private/Install-WUServicingStackUpdate.ps1

function Install-WUServicingStackUpdate {
    <#
    .SYNOPSIS
    Automatically downloads and installs the latest Servicing Stack Update (SSU) for the current Windows build
 
    .DESCRIPTION
    This function attempts to automatically resolve exit code 193 DISM failures by installing the latest SSU.
    It downloads the SSU from Microsoft Update Catalog and installs it using dism.exe or Windows Update standalone installer.
 
    .OUTPUTS
    PSCustomObject with Success boolean and Message string
 
    .NOTES
    Based on community patterns from OSDeploy, MSEndpointMgr, and other repositories for automated SSU installation.
    #>


    [CmdletBinding()]
    param()

    $result = [PSCustomObject]@{
        Success = $false
        Message = ""
        SSUInstalled = $false
        InstalledKB = ""
    }

    try {
        Write-WULog -Message "Starting automated SSU installation process..." -Level "Info"

        # Get current OS information
        $osInfo = Get-WmiObject -Class Win32_OperatingSystem
        $buildNumber = $osInfo.BuildNumber
        $architecture = if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" }

        Write-WULog -Message "Detected OS Build: $buildNumber, Architecture: $architecture" -Level "Info"

        # Create temporary download directory
        $tempDir = Join-Path $env:TEMP "SSU_Download_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
        if (-not (Test-Path $tempDir)) {
            New-Item -Path $tempDir -ItemType Directory -Force | Out-Null
        }

        Write-WULog -Message "Created temporary directory: $tempDir" -Level "Info"

        # Define known SSU download patterns based on Windows build
        $ssuPatterns = @{
            # Windows 10 builds
            "19041" = @{ # 2004
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "x86" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x86_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 10 Version 2004"
            }
            "19042" = @{ # 20H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "x86" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x86_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 10 Version 20H2"
            }
            "19043" = @{ # 21H1
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "x86" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x86_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 10 Version 21H1"
            }
            "19044" = @{ # 21H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "x86" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x86_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 10 Version 21H2"
            }
            "19045" = @{ # 22H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "x86" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x86_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 10 Version 22H2"
            }
            # Windows 11 builds
            "22000" = @{ # 21H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 11"
            }
            "22621" = @{ # 22H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 11 Version 22H2"
            }
            "22631" = @{ # 23H2
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 11 Version 23H2"
            }
            "26100" = @{ # 24H2 - Bleeding edge build
                "x64" = "https://catalog.s.download.windowsupdate.com/c/msdownload/update/software/secu/*/windows10.0-kb*-x64_*.msu"
                "searchTerm" = "Servicing Stack Update for Windows 11 Version 24H2"
            }
        }

        # Try Windows Update method first (most reliable)
        Write-WULog -Message "Attempting to install SSU via Windows Update PowerShell module..." -Level "Info"
        
        try {
            # Check if PSWindowsUpdate module is available
            if (Get-Module -ListAvailable -Name PSWindowsUpdate) {
                Import-Module PSWindowsUpdate -Force
                
                # Search for SSU updates
                $allSecurityUpdates = Get-WindowsUpdate -Category "Security Updates" -AcceptAll
                $ssuUpdates = $allSecurityUpdates | Where-Object { $_.Title -like "*Servicing Stack*" }
                
                if ($ssuUpdates) {
                    Write-WULog -Message "Found $($ssuUpdates.Count) SSU update(s) via Windows Update" -Level "Info"
                    
                    # Install the most recent SSU
                    $installResult = Install-WindowsUpdate -KBArticleID $ssuUpdates[0].KBArticleID -AcceptAll -IgnoreReboot
                    
                    if ($installResult.ResultCode -eq 2) { # Succeeded
                        $result.Success = $true
                        $result.SSUInstalled = $true
                        $result.InstalledKB = $ssuUpdates[0].KBArticleID
                        $result.Message = "Successfully installed SSU via Windows Update: $($ssuUpdates[0].KBArticleID)"
                        Write-WULog -Message $result.Message -Level "Success"
                        return $result
                    }
                }
            }
        }
        catch {
            Write-WULog -Message "Windows Update method failed: $($_.Exception.Message)" -Level "Warning"
        }

        # Alternative: Use DISM to check for pending SSU packages
        Write-WULog -Message "Checking for pending SSU packages in Windows image..." -Level "Info"
        
        try {
            $pendingPackages = dism.exe /online /get-packages | Where-Object { $_ -like "*Servicing Stack*" -and $_ -like "*Pending*" }
            
            if ($pendingPackages) {
                Write-WULog -Message "Found pending SSU packages. Attempting to commit..." -Level "Info"
                
                # Commit pending packages
                $commitResult = dism.exe /online /cleanup-image /restorehealth /source:WU
                $commitExitCode = $LASTEXITCODE
                
                if ($commitExitCode -eq 0) {
                    $result.Success = $true
                    $result.SSUInstalled = $true
                    $result.Message = "Successfully committed pending SSU packages"
                    Write-WULog -Message $result.Message -Level "Success"
                    return $result
                }
            }
        }
        catch {
            Write-WULog -Message "DISM pending packages check failed: $($_.Exception.Message)" -Level "Warning"
        }

        # Alternative: Try using Windows Update API directly
        Write-WULog -Message "Attempting to use Windows Update API for SSU installation..." -Level "Info"
        
        try {
            # Create Windows Update session
            $updateSession = New-Object -ComObject Microsoft.Update.Session
            $updateSearcher = $updateSession.CreateUpdateSearcher()
            
            # Search for SSU updates
            $searchResult = $updateSearcher.Search("Type='Software' and IsHidden=0 and IsInstalled=0 and CategoryIDs contains '28bc880e-0592-4cbf-8f95-c79b17911d5f'")
            
            if ($searchResult.Updates.Count -gt 0) {
                Write-WULog -Message "Found $($searchResult.Updates.Count) SSU update(s) via Windows Update API" -Level "Info"
                
                # Filter for actual SSU updates
                $ssuUpdate = $searchResult.Updates | Where-Object { $_.Title -like "*Servicing Stack Update*" } | Select-Object -First 1
                
                if ($ssuUpdate) {
                    Write-WULog -Message "Installing SSU: $($ssuUpdate.Title)" -Level "Info"
                    
                    # Create update collection and add the SSU
                    $updateCollection = New-Object -ComObject Microsoft.Update.UpdateColl
                    $updateCollection.Add($ssuUpdate)
                    
                    # Download and install
                    $downloader = $updateSession.CreateUpdateDownloader()
                    $downloader.Updates = $updateCollection
                    $downloadResult = $downloader.Download()
                    
                    if ($downloadResult.ResultCode -eq 2) { # Success
                        $installer = $updateSession.CreateUpdateInstaller()
                        $installer.Updates = $updateCollection
                        $installResult = $installer.Install()
                        
                        if ($installResult.ResultCode -eq 2) { # Success
                            $result.Success = $true
                            $result.SSUInstalled = $true
                            $result.InstalledKB = $ssuUpdate.KBArticleIDs | Select-Object -First 1
                            $result.Message = "Successfully installed SSU via Windows Update API: $($ssuUpdate.Title)"
                            Write-WULog -Message $result.Message -Level "Success"
                            return $result
                        }
                    }
                }
            }
        }
        catch {
            Write-WULog -Message "Windows Update API method failed: $($_.Exception.Message)" -Level "Warning"
        }

        # Fallback: Manual detection and guidance
        Write-WULog -Message "Automated SSU installation methods failed. Providing manual guidance..." -Level "Warning"
        
        $manualGuidance = @"
MANUAL SSU INSTALLATION REQUIRED:
 
1. Visit Microsoft Update Catalog: https://www.catalog.update.microsoft.com/
2. Search for: 'Servicing Stack Update Windows $buildNumber $architecture'
3. Download the latest SSU for your build ($buildNumber) and architecture ($architecture)
4. Install using: wusa.exe <downloaded_file>.msu /quiet /norestart
5. Restart your computer if required
6. Re-run the component store repair
 
Alternative: Use Windows Update Settings to check for and install available updates.
 
WINDOWS 11 24H2 SPECIFIC NOTES:
- Build 26100 is a bleeding-edge build that may require latest insider SSUs
- If standard SSU fails, try Windows 11 Installation Media repair method
- Consider using DISM with installation source: /source:wim:install.wim:1 /limitaccess
"@


        $result.Message = $manualGuidance
        Write-WULog -Message "SSU installation guidance provided for manual intervention" -Level "Warning"
        Write-WULog -Message $manualGuidance -Level "Info"

        return $result
    }
    catch {
        $result.Message = "SSU installation failed: $($_.Exception.Message)"
        Write-WULog -Message $result.Message -Level "Error"
        return $result
    }
    finally {
        # Cleanup temporary directory
        if (Test-Path $tempDir) {
            try {
                Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
                Write-WULog -Message "Cleaned up temporary directory: $tempDir" -Level "Info"
            }
            catch {
                Write-WULog -Message "Could not clean up temporary directory: $($_.Exception.Message)" -Level "Warning"
            }
        }
    }
}