-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInstall-WSUSUpdatesMicrosoftFallback.ps1
More file actions
265 lines (211 loc) · 10.8 KB
/
Install-WSUSUpdatesMicrosoftFallback.ps1
File metadata and controls
265 lines (211 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#Requires -Version 5.1
#Requires -RunAsAdministrator
Function Install-WsusUpdates {
<#
.SYNOPSIS
This cmdlet is used to scan, download, and install WSUS approved Windows Updates and optionally restart.
.DESCRIPTION
Uses the Windows Update Agent (WUA) COM API for reliable patching on Server 2016/2019/2022 (and 2025).
Optionally triggers a post-install UsoClient scan verb (best-effort) to refresh reporting/status.
.PARAMETER NoReboot
Switch parameter to specify you do NOT want to reboot automatically even if required.
.PARAMETER IncludePreview
Switch parameter to allow installation of Preview updates.
.EXAMPLE
Install-WsusUpdates
# Downloads and installs WSUS approved updates and reboots if required.
.EXAMPLE
Install-WsusUpdates -NoReboot
# Downloads and installs WSUS approved updates but does not reboot automatically.
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
- Recommended to run via Task Scheduler as SYSTEM with highest privileges.
- Respects machine update source configuration (WSUS if configured via policy).
.LINK
https://github.com/tobor88
https://github.com/OsbornePro
https://www.powershellgallery.com/profiles/tobor
https://osbornepro.com
https://writeups.osbornepro.com
https://btpssecpack.osbornepro.com
https://www.powershellgallery.com/profiles/tobor
https://www.hackthebox.eu/profile/52286
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
#>
[OutputType([System.Management.Automation.PSObject])]
[CmdletBinding()]
param(
[Parameter(
Mandatory=$False
)] # End Parameter
[Switch]$NoReboot,
[Parameter(
Mandatory=$False
)] # End Parameter
[Switch]$IncludePreview
) # End param
$InformationPreference = "Continue"
Function Test-IsWsusConfigured {
$AuKey = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
$WuKey = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
Try {
$UseWUServer = (Get-ItemProperty -Path $AuKey -Name UseWUServer -ErrorAction Stop).UseWUServer
$WUServer = (Get-ItemProperty -Path $WuKey -Name WUServer -ErrorAction Stop).WUServer
If ($UseWUServer -eq 1 -and [String]::IsNullOrWhiteSpace($WUServer) -eq $False) {
Return $True
} Else {
Return $False
} # End If Else
} Catch {
Return $False
} # End Try Catch
} # End Function Test-IsWsusConfigured
# Select UsoClient verb based on OS
$OS = Get-CimInstance -ClassName Win32_OperatingSystem -Verbose:$False | Select-Object -ExpandProperty Caption
Write-Verbose -Message "OS Version discovered - $OS"
Switch -Wildcard ($OS) {
"Windows Server 2016*" {
$Verb = "StartInteractiveScan"
} "Windows Server 2019*" {
$Verb = "StartInteractiveScan"
} "Windows Server 2022*" {
$Verb = "StartInteractiveScan"
} "Windows Server 2025*" {
$Verb = "StartInteractiveScan"
} Default {
$Verb = "StartScan"
} # End Switch Options
} # End Switch
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Starting WSUS patch run on: $OS"
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Running as: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
If (Test-IsWsusConfigured) {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') WSUS policy detected (UseWUServer/WUServer present)."
} Else {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') WARNING: WSUS policy not detected. This host may use Microsoft Update instead."
} # End If Else
# Ensure core services are running
$Services = @("wuauserv","bits","cryptsvc","trustedinstaller")
ForEach ($SvcName in $Services) {
Try {
$Svc = Get-Service -Name $SvcName -ErrorAction Stop
If ($Svc.Status -ne 'Running') {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Starting service: $SvcName"
Start-Service -Name $SvcName -ErrorAction Stop
} # End If
} Catch {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') WARNING: Could not check/start service '$SvcName' - $($_.Exception.Message)"
} # End Try Catch
} # End ForEach
# WUA COM: Search -> Download -> Install
Try {
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
# Criteria notes:
# - IsAssigned=1 tends to align with “offered/approved” updates in managed environments.
# - Type='Software' excludes drivers. Remove if you want drivers too.
$Criteria = "IsInstalled=0 and IsHidden=0 and Type='Software' and IsAssigned=1"
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Searching for updates with criteria: $Criteria"
$SearchResult = $Searcher.Search($Criteria)
$FoundCount = $SearchResult.Updates.Count
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Updates found: $FoundCount"
If ($FoundCount -eq 0) {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') No applicable updates. Exiting."
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Finished WSUS patch run"
Return [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
OS = $OS
UpdatesFound = 0
UpdatesQueued = 0
DownloadResult = $Null
InstallResult = $Null
RebootRequired = $False
}
} # End If
$UpdatesToInstall = New-Object -ComObject Microsoft.Update.UpdateColl
For ($i = 0; $i -lt $FoundCount; $i++) {
$Update = $SearchResult.Updates.Item($i)
If (-Not $IncludePreview.IsPresent -and $Update.Title -match "Preview") {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Skipping preview update: $($Update.Title)"
Continue
} # End If
If (-Not $Update.EulaAccepted) {
Try { $Update.AcceptEula() | Out-Null } Catch { }
} # End If
[Void]$UpdatesToInstall.Add($Update)
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Queued: $($Update.Title)"
} # End For
If ($UpdatesToInstall.Count -eq 0) {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') After filtering, nothing to install. Exiting."
Return [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
OS = $OS
UpdatesFound = $FoundCount
UpdatesQueued = 0
DownloadResult = $Null
InstallResult = $Null
RebootRequired = $False
}
} # End If
# Download
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Downloading $($UpdatesToInstall.Count) update(s)"
$Downloader = $Session.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToInstall
$DownloadResult = $Downloader.Download()
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Download ResultCode: $($DownloadResult.ResultCode)"
# Install
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Installing $($UpdatesToInstall.Count) update(s)"
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Installing $($UpdatesToInstall.Count) update(s)..."
$Installer = $Session.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallResult = $Installer.Install()
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Install ResultCode: $($InstallResult.ResultCode)"
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') RebootRequired: $($InstallResult.RebootRequired)"
# Per-update results
For ($i = 0; $i -lt $UpdatesToInstall.Count; $i++) {
$Title = $UpdatesToInstall.Item($i).Title
$Rc = $InstallResult.GetUpdateResult($i).ResultCode
$Hr = '{0:x8}' -f ($InstallResult.GetUpdateResult($i).HResult -band 0xffffffff)
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Result: [$($Rc)] HResult=0x$($Hr) - $($Title)"
} # End For
} Catch {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') ERROR: $($_.Exception.Message)"
Throw
} Finally {
# Trigger a scan/reporting verb after install
Try {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Best-effort: triggering UsoClient verb '$Verb' to refresh scan/reporting."
Start-Process -FilePath "$($env:SystemRoot)\System32\UsoClient.exe" -ArgumentList $Verb -NoNewWindow -ErrorAction SilentlyContinue | Out-Null
} Catch {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') WARNING: Failed to run UsoClient.exe $Verb - $($_.Exception.Message)"
} # End Try Catch
} # End Try Catch Finally
If ($InstallResult.RebootRequired -and (-Not $NoReboot.IsPresent)) {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Restarting system to complete updates."
Restart-Computer -Force
} ElseIf ($InstallResult.RebootRequired -and $NoReboot.IsPresent) {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Reboot is required but NoReboot was specified. Not restarting automatically."
} Else {
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') No reboot required."
} # End If ElseIf Else
Write-Verbose -Message "[v] $(Get-Date -Format 'MM-dd-yyyy hh:mm:ss') Finished WSUS patch run"
Return [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
OS = $OS
UpdatesFound = $FoundCount
UpdatesQueued = $UpdatesToInstall.Count
DownloadResult = $DownloadResult.ResultCode
InstallResult = $InstallResult.ResultCode
RebootRequired = $InstallResult.RebootRequired
UsoClientVerb = $Verb
LogFile = $LogFile
}
} # End Function Install-WsusUpdates
Start-Transcript -Path "C:\Windows\Temp\WSUS-Update-Task.log" -Append -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Try {
Install-WsusUpdates -Verbose
} Finally {
Stop-Transcript -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
} # End Try Finally