PowerShell script to force download and install WindowsUpdates

I have been using the UpdateHF.vbs vbscript for years to patch all my servers. I wrote a simple HTA to wrap it, and it gets executed by psexec. I wanted to take that script, strip it down, and convert it to PowerShell. My intension was to  run it through a PSSession but I get access denied. Maybe I will try launching it with SCCM?

I found these three scripts, that I chopped to together for a script that I wanted:

Function JBMURPHY-Install-WindowsUpdates {
PARAM([switch]$Install,[switch]$reboot)
	if($(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired")){
		if (!($reboot)){
    		write-host "There are pending reboots, please pass the reboot command"
    		return
		}
		else{
		restart-computer
		return
		}
	}

	Write-Host -nonewline " + Searching for Updates: "
	$UpdateSession = New-Object -ComObject Microsoft.Update.Session
	$Updates=$updateSession.CreateupdateSearcher().Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0").Updates
	Write-Host " Found [$($Updates.count)] Updates to Download and install`n`n"

	$UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
	$UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
	foreach ($Update in $Updates){

		# Add Update to Collection
		if ( $Update.EulaAccepted -eq 0 ) { $Update.AcceptEula() }
		$UpdatesCollection.Add($Update) | out-null

		# Download
		Write-Host -NoNewline " + Downloading Update $($Update.Title)"
		$UpdatesDownloader.Updates = $UpdatesCollection
		$DownloadResult = $UpdatesDownloader.Download()
		$DownloadResultResultCode = switch -exact ($DownloadResult.ResultCode)
		{
		  0   {"NotStarted"}
		  1   {"InProgress"}
		  2   {"Succeeded"}
		  3   {"SucceededWithErrors"}
		  4   {"Failed"}
		  5   {"Aborted"}
		}
		$Message = " [{0}] " -f ($DownloadResultResultCode)
		Write-Host -ForegroundColor Green $message
	}
	if (($Install) -and ($($Updates.count) -gt 0)) {
	write-host "`n`nInstalling updates"
	$Installer = $UpdateSession.CreateUpdateInstaller()
	$Installer.Updates = $UpdatesCollection
	$InstallerResult = $Installer.Install()
	$InstallerResultCode = switch -exact ($InstallerResult.ResultCode)
		{
		  0   {"NotStarted"}
		  1   {"InProgress"}
		  2   {"Succeeded"}
		  3   {"SucceededWithErrors"}
		  4   {"Failed"}
		  5   {"Aborted"}
		}
		$Message = " Installation [{0}] " -f ($InstallerResultCode)
		Write-Host $message
		Write-Host
	}
	if (($reboot) -and ($($Updates.count) -gt 0)) {
	if($(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"))
		{
    		write-host "Rebooting"
    		restart-computer
		}
	}
}

Thanks to those that put the original scripts together

,

Comments are closed.

Powered by WordPress. Designed by WooThemes