function InstallationResultToText($result) { switch ($result) { 2 { "Succeeded" } 3 { "Succeeded with errors" } 4 { "Failed" } 5 { "Cancelled" } default { "Unexpected ($result)" } } } Write-Host "--- Running Windows Update ---" Write-Host "Searching for updates..." Write-Host "" $updateSession = new-object -com "Microsoft.Update.Session" $updateSearcher = $updateSession.CreateupdateSearcher() $criteria = "IsInstalled=0 and Type='Software' and IsHidden=0" $searchResult = $updateSearcher.Search($criteria) Write-Host "List of applicable items on the machine:" if ($searchResult.Updates.Count -eq 0) { Write-Host "There are no applicable updates." exit 0 } else { $downloadReq = $False $i = 0 foreach ($update in $searchResult.Updates){ $i++ if ( $update.IsDownloaded ) { Write-Host $i">" $update.Title "(downloaded)" } else { $downloadReq = $true Write-Host $i">" $update.Title "(not downloaded)" } } } if ( $downloadReq ) { Write-Host "" Write-Host "Creating collection of updates to download..." $updatesToDownload = new-object -com "Microsoft.Update.UpdateColl" foreach ($update in $searchResult.Updates){ $updatesToDownload.Add($update) | out-null } Write-Host "Downloading updates..." $downloader = $updateSession.CreateUpdateDownloader() $downloader.Updates = $updatesToDownload $downloader.Download() Write-Host "List of downloaded updates:" $i = 0 foreach ($update in $searchResult.Updates){ $i++ if ( $update.IsDownloaded ) { Write-Host $i">" $update.Title "(downloaded)" } else { Write-Host $i">" $update.Title "(not downloaded)" } } } else { Write-Host "All updates are already downloaded." } $updatesToInstall = new-object -com "Microsoft.Update.UpdateColl" Write-Host "" Write-Host "Creating collection of downloaded updates to install..." foreach ($update in $searchResult.Updates){ if ( $update.IsDownloaded ) { $updatesToInstall.Add($update) | out-null } } $returnValue = 0 if ( $updatesToInstall.Count -eq 0 ) { Write-Host "Not ready for installation." } else { Write-Host "Installing" $updatesToInstall.Count "updates..." $installer = $updateSession.CreateUpdateInstaller() $installer.Updates = $updatesToInstall $installationResult = $installer.Install() if ( $installationResult.ResultCode -eq 2 ) { Write-Host "All updates installed successfully." } else { Write-Host "Some updates could not installed." } $returnValue = $installationResult.ResultCode if ( $installationResult.RebootRequired ) { Write-Host "One or more updates are requiring reboot." $returnValue = $returnValue + 100 } else { Write-Host "Finished. Reboot are not required." } Write-Host "" Write-Host "Listing of updates installed and indivisual installation results:" $i = 0 foreach ($update in $updatesToInstall){ $result = $installationResult.GetUpdateResult($i) $i++ Write-Host $i">" $update.Title ":" $(InstallationResultToText $result.ResultCode) ", HRESULT:" $($result.HResult) } } Exit $returnValue