# Install available software updates from the configured Windows Update source. # See https://learn.microsoft.com/windows/win32/wua_sdk/windows-update-agent-object-model $ErrorActionPreference = 'Stop' $session = New-Object -ComObject Microsoft.Update.Session $session.ClientApplicationID = 'Rust Discovery' $searcher = $session.CreateUpdateSearcher() $search = $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'") if ($search.ResultCode -ne 2) { throw "Update search returned $($search.ResultCode)" } $failed = $false $systemInfo = New-Object -ComObject Microsoft.Update.SystemInfo if ($systemInfo.RebootRequired) { Write-Output '{"reboot_required":true,"status":"restart_pending"}' exit 1 } foreach ($update in $search.Updates) { $result = [ordered]@{ id = $update.Identity.UpdateID; title = $update.Title; status = 'pending' } try { if ($update.InstallationBehavior.CanRequestUserInput -or !$update.EulaAccepted) { $result.status = 'operator_input_required' $failed = $true } else { $batch = New-Object -ComObject Microsoft.Update.UpdateColl [void]$batch.Add($update) if (!$update.IsDownloaded) { $downloader = $session.CreateUpdateDownloader() $downloader.Updates = $batch $download = $downloader.Download().GetUpdateResult(0) if ($download.ResultCode -ne 2) { throw "Download HRESULT $($download.HResult)" } } $installer = $session.CreateUpdateInstaller() $installer.AllowSourcePrompts = $false $installer.Updates = $batch $install = $installer.Install().GetUpdateResult(0) $result.status = [int]$install.ResultCode $result.hresult = $install.HResult $result.reboot_required = [bool]$install.RebootRequired if ($install.ResultCode -ne 2) { $failed = $true } } } catch { $result.status = 'failed' $result.error = $_.Exception.Message $failed = $true } Write-Output ($result | ConvertTo-Json -Compress) } Write-Output (@{ found = $search.Updates.Count; reboot_required = [bool]$systemInfo.RebootRequired } | ConvertTo-Json -Compress) if ($failed) { exit 1 }