Skip to content

Instantly share code, notes, and snippets.

@hikoma
Last active January 27, 2017 20:36
Show Gist options
  • Save hikoma/11164498 to your computer and use it in GitHub Desktop.
Save hikoma/11164498 to your computer and use it in GitHub Desktop.
Run windows update from powershell
Function Install-WindowsUpdate {
[CmdletBinding()]
Param ()
Process {
$updateSession = New-Object -ComObject "Microsoft.Update.Session"
Write-Host "Searching updates..."
$searcher = $updateSession.CreateupdateSearcher()
$searchResult = $searcher.Search("IsInstalled=0 and AutoSelectOnWebSites=1")
if ($searchResult.Updates.Count -eq 0) {
Write-Host "There are no updates"
return
} else {
Write-Host "Found following updates"
$searchResult.Updates | Format-Table -AutoSize IsDownloaded, MaxDownloadSize, Title
}
Write-Host "Downloading updates..."
$downloader = $updateSession.CreateUpdateDownloader()
$downloader.Updates = $searchResult.Updates
$downloadResult = $downloader.Download()
if ($downloadResult.ResultCode -ne 2) {
throw $downloadResult
}
Write-Host "Installing updates..."
$updatesToInstall = New-Object -ComObject "Microsoft.Update.UpdateColl"
$searchResult.Updates | ? { $_.IsDownloaded } | %{ $updatesToInstall.Add($_) } | Out-Null
$installer = $updateSession.CreateUpdateInstaller()
$installer.Updates = $updatesToInstall
$installResult = $installer.Install()
if ($installResult.ResultCode -ne 2) {
throw $installResult
}
if ($installResult.RebootRequired) {
if ($PSCmdlet.ShouldProcess('Restart Computer')) {
Restart-Computer
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment