Skip to content

Instantly share code, notes, and snippets.

@onyxhat
Created July 23, 2014 15:20
Show Gist options
  • Save onyxhat/650121af37bcb4fefe71 to your computer and use it in GitHub Desktop.
Save onyxhat/650121af37bcb4fefe71 to your computer and use it in GitHub Desktop.
$Host.UI.RawUI.WindowTitle = "-=Windows Update=-"
$Script = $MyInvocation.MyCommand.Definition
Write-Host -NoNewline "Checking for Updates..."
$UpdateSession = New-Object -Com Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
}
If ($SearchResult.Updates.Count -eq 0) {
Write-Host "NONE!"
Exit
}
Write-Host "DONE!"
$UpdatesToDownload = New-Object -Com Microsoft.Update.UpdateColl
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
$Null = $UpdatesToDownload.Add($Update)
}
Write-Host -NoNewline "Downloading Updates..."
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Null = $Downloader.Download()
$UpdatesToInstall = New-Object -Com Microsoft.Update.UpdateColl
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
If ($Update.IsDownloaded) {
$Null = $UpdatesToInstall.Add($Update)
}
}
Write-Host "DONE!"
Write-Host -NoNewline "Installing Updates..."
$Installer = $UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
Write-Host "DONE!"
If ($InstallationResult.RebootRequired -eq $True) {
Copy-Item -Path $Script -Destination ($env:SystemDrive + "\") -Force | Out-Null
New-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce -Name "WSUS" -Value "$PSHOME\powershell.exe -Command `"& $($env:SystemDrive + "\" + (Split-Path -Leaf $Script))`"" | Out-Null
}
Add-Content (Join-Path (Split-Path $Script -Parent) "updates.log") $("Date: " + $(Get-Date) + " --- Updates: " + $UpdatesToInstall.Count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment