Last active
August 29, 2015 14:22
-
-
Save BladeFireLight/17778f1ce3248b11535e to your computer and use it in GitHub Desktop.
WindowsUpdate script for use with Start-ImageBuild.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -Version 2 | |
Function Add-WindowsUpdate | |
{ | |
param ( | |
[string]$Criteria = "IsInstalled=0 and Type='Software'" , | |
[switch]$AutoRestart, | |
[Switch]$ShutdownAfterUpdate, | |
[switch]$ForceRestart, | |
[Switch]$ShutdownOnNoUpdate | |
) | |
$resultcode = @{ | |
0 = 'Not Started' | |
1 = 'In Progress' | |
2 = 'Succeeded' | |
3 = 'Succeeded With Errors' | |
4 = 'Failed' | |
5 = 'Aborted' | |
} | |
$updateSession = New-Object -ComObject 'Microsoft.Update.Session' | |
Write-Progress -Activity 'Updating' -Status 'Checking available updates' | |
$updates = $updateSession.CreateupdateSearcher().Search($Criteria).Updates | |
$updates | |
if ($updates.Count -eq 0) | |
{ | |
Write-Verbose -Message 'There are no applicable updates.' -Verbose | |
if ($ShutdownOnNoUpdate) | |
{ | |
Stop-Computer | |
} | |
} | |
else | |
{ | |
$downloader = $updateSession.CreateUpdateDownloader() | |
$downloader.Updates = $updates | |
Write-Progress -Activity 'Updating' -Status "Downloading $($downloader.Updates.count) updates" | |
$Result = $downloader.Download() | |
$Result | |
if (($Result.Hresult -eq 0) -and (($Result.resultCode -eq 2) -or ($Result.resultCode -eq 3)) ) | |
{ | |
$updatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl' | |
$updates | | |
Where-Object -FilterScript { | |
$_.isdownloaded | |
} | | |
ForEach-Object -Process { | |
$null = $updatesToInstall.Add($_) | |
} | |
$installer = $updateSession.CreateUpdateInstaller() | |
$installer.Updates = $updatesToInstall | |
Write-Progress -Activity 'Updating' -Status "Installing $($installer.Updates.count) updates" | |
$installationResult = $installer.Install() | |
$installationResult | |
$Global:counter = -1 | |
$installer.updates | Format-Table -AutoSize -Property Title, EulaAccepted, @{ | |
label = 'Result' | |
expression = { | |
$resultcode[$installationResult.GetUpdateResult($Global:counter++).resultCode ] | |
} | |
} | |
if ($AutoRestart -and $installationResult.rebootRequired) | |
{ | |
Restart-Computer | |
} | |
if ($ForceRestart) | |
{ | |
Restart-Computer | |
} | |
if ($ShutdownAfterUpdate) | |
{ | |
Stop-Computer | |
} | |
} | |
} | |
} | |
Start-Transcript -Path $PSScriptRoot\Patch.log | |
Add-WindowsUpdate -ForceRestart -ShutdownOnNoUpdate | |
Stop-Transcript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment