-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsUpdatesHelper.ps1
More file actions
2106 lines (1772 loc) · 88.1 KB
/
WindowsUpdatesHelper.ps1
File metadata and controls
2106 lines (1772 loc) · 88.1 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Installs Windows Updates using the supported WUA COM API, with optional download, controlled reboot (now or scheduled), and detailed logging.
.DESCRIPTION
SPECIAL SHOW UPDATE HISTORY MODE
---------------------------------
If -ShowHistory is used, the script does NOT install/download/reboot.
Instead it queries Windows Update history (same source as the GUI "View update history"),
optionally filtered, and then exits.
NORMAL INSTALL UPDATES MODE
----------------------------
By default(without -ShowHistory) it installs Windows updates like this:
- Installs already downloaded updates if any.
- With -Download, will also download all required updates.
- With -Reboot, will reboot after installation if needed (or regardless with -RebootAnyway).
Batches "normal" updates together; installs "exclusive" updates one-by-one; accepts EULAs.
Robustness:
Service start is retried up to 3x with exponential delays (5s, 10s, 20s) before failing.
Pending reboot detection uses WU `RebootRequired` and CBS `RebootPending`.
Post-download refresh search has a catch/fallback: if the refresh search throws, proceeds using the initial search results (with a warning).
Uses only supported, inbox components (no extra modules, no `UsoClient`, PS 5.1-safe syntax).
Reboot is first tried without /f and after a few minutes with /f.
If an update (e.g. Servicing Stack) installs and immediately requires a reboot; subsequent updates will fail with 0x80240030 until reboot. If such failures are detected and the script was run with -Reboot or -RebootAnyway,
the script will ensure continuation of installations after the reboot like this:
- Create a temporary scheduled task that runs this script again
at startup with -XXX_ResumeAfterReboot.
- On that second automated run with -XXX_ResumeAfterReboot:
- The startup task is removed and the script continues as normal (install + maybe reboot).
Logging:
- Logs everything to WindowsUpdateHelper-YYYY-MM-DD.log
1. If C:\IT\LOG exists, log is created there.
2. Else if C:\IT\LOGS exists, there.
3. Else in the system temp folder.
.PARAMETER Download
Perform online scan and download applicable updates that are not yet downloaded, then proceed to install everything downloaded.
.PARAMETER Reboot
After installation, reboot only if updates require it (or regardless if -RebootAnyway is also used).
.PARAMETER Interactive
If specified, the script will include updates flagged as InstallationBehavior.CanRequestUserInput
(Like some drivers/firmware that show GUI prompts and wait for user actions -- e.g. clicking "Accept").
Without this switch, such updates are skipped.
Alias: -CanRequestUserInput
.PARAMETER RebootAnyway
Reboot regardless of whether updates require it (implies -Reboot).
.PARAMETER XXX_ResumeAfterReboot
DO NOT USE THIS SWITCH. It is used INTERNALLY to continue installations after a reboot.
.PARAMETER AbortReboot
Abort a reboot initiated by this script
.PARAMETER XXX_RebootNow
DO NOT USE THIS SWITCH. It is used INTERNALLY to force a reboot.
.PARAMETER XXX_RebootArmedAt
DO NOT USE THIS SWITCH. It is used INTERNALLY to avoid rebooting if a reboot already occured after this time.
.PARAMETER ShowHistory
List Windows Update history (no install/download/reboot) and exit.
.PARAMETER MaxResults
(ShowHistory mode) Maximum number of matching history entries to output. Default: 30. Use 0 to return all matches found (within MaxScanEntries).
.PARAMETER LastDays
(ShowHistory mode) Only include history entries from the last N days.
.PARAMETER IncludeAV
(ShowHistory mode) Include KB2267602 (Defender definitions) entries (excluded by default).
.PARAMETER MaxScanEntries
(ShowHistory mode) Safety cap: maximum number of history rows to scan. Default: 10000.
.PARAMETER ListRecentLogs
List this script's log files and exit. Returns FileInfo objects sorted by LastWriteTime (oldest -> newest; most recent last).
By default it returns the most recent 10 log files.
.PARAMETER ListAll
Used only with -ListRecentLogs. If specified, returns all log files that can be found (instead of only the most recent 10).
.PARAMETER InstallOptional
Installs an optional update (needs the update ID)
.EXAMPLE
# Install any already downloaded updates and reboot if needed:
.\WindowsUpdatesHelper.ps1 -Reboot
# Download, Install and if needed reboot:
.\WindowsUpdatesHelper.ps1 -Download -Reboot
# Download, Install and reboot regardless of whether updates require it:
.\WindowsUpdatesHelper.ps1 -Download -Reboot -RebootAnyway
# Show latest Windows Update history entries:
.\WindowsUpdatesHelper.ps1 -ShowHistory
# Show latest Windows Update history entries, include AV updates:
.\WindowsUpdatesHelper.ps1 -ShowHistory -LastDays 14 -IncludeAV
# List the most recent 10 log files created by this script (most recent last):
.\WindowsUpdatesHelper.ps1 -ListRecentLogs
#>
<#
=== TODO ===
* Interactive updates should be defered as long as possible:
Without -Reboot:
We should first try to install everything that is
Non-interactive, then try to install interactive ones.
With -Reboot:
We should first try to install everything that is
Non-interactive, reboot as necessary, then try to install
interactive ones then again reboot as necessary.
(For the moment I have logic that never reboots a 2nd time
I must adjust it for this case)
* Detect if another version of this script is already running
Notify user accordingly
* React to these access denied errors that are thrown if you run this script from within Enter-PSSession.
I can probably create a throwaway scheduled task that will execute the script with the same arguments.
Downloading 1 update(s)...
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [WindowsUpdatesHelper.ps1], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,WindowsUpdatesHelper.ps1
Installing 1 normal update(s) as a batch...
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [WindowsUpdatesHelper.ps1], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,WindowsUpdatesHelper.ps1
#>
[CmdletBinding(PositionalBinding=$false, DefaultParameterSetName='Install')]
param(
[Parameter(ParameterSetName='Install')][switch]$Download,
[Parameter(ParameterSetName='Install')][switch]$Reboot,
[Parameter(ParameterSetName='Install')][switch]$RebootAnyway,
[Parameter(ParameterSetName='Install')][Alias('CanRequestUserInput')][switch]$Interactive,
[Parameter(ParameterSetName='Install')][switch]$XXX_ResumeAfterReboot,
[Parameter(ParameterSetName='History', Mandatory=$true)][switch]$ShowHistory,
[Parameter(ParameterSetName='History')][int]$MaxResults = 30,
[Parameter(ParameterSetName='History')][int]$LastDays,
[Parameter(ParameterSetName='History')][switch]$IncludeAV,
[Parameter(ParameterSetName='History')][int]$MaxScanEntries = 10000,
[Parameter(ParameterSetName='Logs', Mandatory=$true)][switch]$ListRecentLogs,
[Parameter(ParameterSetName='Logs')][switch]$ListAll,
[Parameter(ParameterSetName='Special')][switch]$XXX_RebootNow,
[Parameter(ParameterSetName='Special')][string]$XXX_RebootArmedAt,
[Parameter(ParameterSetName='InstallOptional')][string]$InstallOptional,
[Parameter(ParameterSetName='AbortReboot')][switch]$AbortReboot
)
# -------------------------------------------------------------------------------------------------
# START
# Generic Helper Functions
# -------------------------------------------------------------------------------------------------
function Assert-Elevated {
$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object Security.Principal.WindowsPrincipal $id
if (-not $p.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
throw "Must be run elevated."
}
}
function Test-IsSystemAccount {
$id=[Security.Principal.WindowsIdentity]::GetCurrent()
if($id -and $id.User){ return ($id.User.Value -eq 'S-1-5-18') }
return $false
}
function Test-RebootPending {
$wu = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
$cbs = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
return ($wu -or $cbs)
}
<#
.SYNOPSIS
Writes a labeled debug dump of an object to host output.
.DESCRIPTION
Writes a host-formatted debug block for the supplied label and object.
When Obj is null, it writes a null marker line. When Json is set, it writes
JSON text. Otherwise it writes a CLIXML block delimited by BEGIN/END marker
lines. If dump generation fails, it writes an error line to the host and does
not throw.
.OUTPUTS
None.
.PARAMETER Label
Text shown in the debug header.
.PARAMETER Obj
Value to dump. Null is accepted and produces a null marker line.
.PARAMETER Depth
Maximum serialization depth used for JSON or CLIXML output.
.PARAMETER Json
When set, writes JSON output; otherwise writes CLIXML output.
#>
function Write-DbgDump {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$Label,
[Parameter()][AllowNull()][object]$Obj,
[int]$Depth=20,
[switch]$Json
)
try {
if ($null -eq $Obj) {
Write-Host "`n-----DEBUG $Label = `$null -----" -ForegroundColor Cyan
} else {
if ($Json) {
Write-Host "`n-----DEBUG JSON of $Label -----" -ForegroundColor Cyan
Write-Host -ForegroundColor DarkCyan ($Obj|ConvertTo-Json -Depth $Depth)
} else {
Write-Host ("`n-----BEGIN DEBUG CLIXML of {0} -----" -f $Label) -ForegroundColor Cyan
$xml=[System.Management.Automation.PSSerializer]::Serialize($Obj,$Depth)
Write-Host $xml -ForegroundColor DarkCyan
Write-Host ("-----END DEBUG CLIXML --------------------`n" -f $Label) -ForegroundColor Cyan
}
}
} catch {
Write-Host -ForegroundColor Red "Write-DbgDump exception: $($_.Exception.Message)"
}
}
<#
.SYNOPSIS
Reads a CLIXML debug dump text and returns the deserialized value.
.OUTPUTS
Deserialized object from the CLIXML content.
.DESCRIPTION
Accepts either a full debug dump block produced by Write-DbgDump in CLIXML
mode or raw CLIXML text.
If Text does not contain a CLIXML debug block, the full Text value is treated
as CLIXML input. The function throws if the effective CLIXML input is empty or
cannot be deserialized.
.PARAMETER Text
Input text containing a CLIXML debug block or raw CLIXML text.
.EXAMPLE
$obj = Read-DbgDump -Text $dumpText
#>
function Read-DbgDump {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$Text)
$m=[regex]::Match($Text,'(?ms)-----BEGIN DEBUG CLIXML .*?-----\s*(?<xml>.*?)\s*-----END DEBUG CLIXML .*?-----')
$xml=if($m.Success){$m.Groups['xml'].Value}else{$Text}
if(-not $xml -or -not $xml.Trim()){ throw "Read-DbgDump: empty input." }
try{ [System.Management.Automation.PSSerializer]::Deserialize($xml) }catch{ throw "Read-DbgDump: deserialize failed: $($_.Exception.Message)" }
}
<#
.SYNOPSIS
Starts transcript logging in a timestamped file
.DESCRIPTION
Chooses a log root in this order:
1. C:\IT\LOG
2. C:\IT\LOGS
3. System temp folder
Attempts to start transcript to the chosen file. If that fails, falls back to temp and retries.
Returns the chosen log path and whether transcript was successfully enabled.
.OUTPUTS
PSCustomObject with properties:
- LogFile (string)
- TranscriptEnabled (bool)
#>
function Start-WuTranscript {
[CmdletBinding()]
param()
$logRoot = if (Test-Path 'C:\IT\LOG') { 'C:\IT\LOG' } elseif (Test-Path 'C:\IT\LOGS') { 'C:\IT\LOGS' } else { [System.IO.Path]::GetTempPath().TrimEnd('\') }
$logName = 'WindowsUpdateHelper-{0}.log' -f (Get-Date -Format 'yyyy-MM-dd_HH.mm.ss')
$LogFile = Join-Path $logRoot $logName
$enabled = $false
try {
Start-Transcript -Path $LogFile -Force | Out-Null
$enabled = $true
Write-Host "Logging to file: $LogFile"
} catch {
Write-Host -ForegroundColor Yellow ("WARNING: Failed to start transcript at '{0}'. Error: {1}" -f $LogFile, $_.Exception.Message)
$fallbackRoot = [System.IO.Path]::GetTempPath().TrimEnd('\')
$fallbackFile = Join-Path $fallbackRoot ([System.IO.Path]::GetFileName($LogFile))
if ($fallbackFile -ne $LogFile) {
try {
Start-Transcript -Path $fallbackFile -Append -Force | Out-Null
$LogFile = $fallbackFile
$enabled = $true
Write-Host -ForegroundColor Yellow ("WARNING: Using fallback log file: {0}" -f $LogFile)
} catch {
Write-Host -ForegroundColor Yellow ("WARNING: Failed to start transcript fallback at '{0}'. Error: {1}" -f $fallbackFile, $_.Exception.Message)
}
}
}
[pscustomobject]@{ LogFile = $LogFile; TranscriptEnabled = $enabled }
}
function Get-DescrFromResultCode([int]$rc) {
switch ($rc) {
0 { 'NotStarted' }
1 { 'InProgress' }
2 { 'Succeeded' }
3 { 'SucceededWithErrors' }
4 { 'Failed' }
5 { 'Aborted' }
default { 'Unknown' }
}
}
function Get-DescrFromHResult([int]$hr) {
if ($hr -eq 0) { return 'No error' }
try {
$ex = [System.Runtime.InteropServices.Marshal]::GetExceptionForHR($hr)
if ($ex -and $ex.Message) { return $ex.Message }
} catch { }
'error'
}
# -------------------------------------------------------------------------------------------------
# END
# Generic Helper Functions
# -------------------------------------------------------------------------------------------------
<#
.SYNOPSIS
Registers a scheduled task that runs this script later to force a reboot.
.DESCRIPTION
Creates or replaces a scheduled task named
WindowsUpdateHelper-ForcedReboot.
The task is configured to run this script with internal reboot arguments.
If registration fails, no task is available for the forced reboot path.
.OUTPUTS
Boolean.
True when the task is registered.
False when registration is not completed.
#>
function Register-WuForcedRebootTask {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ScriptPath,[Parameter(Mandatory=$true)][int]$Minutes,[Parameter(Mandatory=$true)][datetime]$ArmedAt)
$taskName='WindowsUpdateHelper-ForcedReboot'
if(-not $ScriptPath){ Write-Host -ForegroundColor Red "ERROR: Tried to schedule a forced reboot but ScriptPath is empty."; return $false }
try{
$psExe=Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$armedAtText=$ArmedAt.ToString('s')
$argLine='-NoLogo -NoProfile -ExecutionPolicy Bypass -File "'+$ScriptPath+'" -XXX_RebootNow -XXX_RebootArmedAt "'+$armedAtText+'"'
$action=New-ScheduledTaskAction -Execute $psExe -Argument $argLine
$runAt=(Get-Date).AddMinutes($Minutes)
$trigger=New-ScheduledTaskTrigger -Once -At $runAt
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null
return $true
} catch {
Write-Host -ForegroundColor Yellow ("ERROR: [ForcedReboot] Failed to register task '{0}': {1}" -f $taskName,$_.Exception.Message)
return $false
}
}
<#
.SYNOPSIS
Registers startup continuation state for a post-reboot rerun.
.DESCRIPTION
Writes a continuation flag file and creates or replaces a startup task named
WindowsUpdateHelper-ResumeAfterReboot.
The function can leave one of the two resources present when the other one
fails to be created.
.OUTPUTS
Boolean.
True when both the flag file and the startup task are created.
False otherwise.
#>
function Register-WuResumeAfterRebootTask {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ScriptPath,[Parameter(Mandatory=$true)][string]$FlagFilePath)
$taskName='WindowsUpdateHelper-ResumeAfterReboot'
$okFlag=$false;$okTask=$false
try{
$now=Get-Date
Set-Content -LiteralPath $FlagFilePath -Value $now.ToString('s') -Encoding ASCII -Force
Write-Output ("[ResumeAfterReboot] Created flag file: {0} (timestamp {1})" -f $FlagFilePath,$now.ToString('s'))
$okFlag=$true
} catch {
Write-Host -ForegroundColor Yellow ("ERROR: [ResumeAfterReboot] Failed to create flag file '{0}': {1}" -f $FlagFilePath,$_.Exception.Message)
}
try{
$psExe=Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$argLine='-NoLogo -NoProfile -ExecutionPolicy Bypass -File "'+$ScriptPath+'" -XXX_ResumeAfterReboot'
$action=New-ScheduledTaskAction -Execute $psExe -Argument $argLine
$trigger=New-ScheduledTaskTrigger -AtStartup
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null
Write-Output ("[ResumeAfterReboot] Registered startup task '{0}' to continue Windows Update after reboot." -f $taskName)
$okTask=$true
} catch {
Write-Host -ForegroundColor Yellow ("ERROR: [ResumeAfterReboot] Failed to register startup task '{0}': {1}" -f $taskName,$_.Exception.Message)
}
return ($okFlag -and $okTask)
}
<#
.SYNOPSIS
Builds the reboot/continuation decision object for the current run.
.OUTPUTS
Produces one psCustomObject:
RebootPendingAtStart : Pending reboot state before install work.
RebootPendingAtEnd : Pending reboot state at evaluation time.
InstalledSomething : True when at least one update installed.
WuaRequestsReboot : True when install results request reboot.
RebootIsNeeded : Script decision about reboot necessity.
InitiateReboot : Script decision to trigger reboot now.
RebootAnyway : Echo of input policy switch.
XXX_ResumeAfterReboot : Echo of internal continuation switch.
BestToRerunAfterReboot : True when another run after reboot is advised.
Has80240030 : True when any result has HResult 0x80240030.
HasFailures : True when any result failed or had errors.
HasSuccesses : True when any result succeeded.
FailedOrErrorResults : Subset of result objects with failures/errors.
AllUpdateResultsCount : Count of supplied result objects.
ShutdownDelaySeconds : Delay used by reboot request path.
ForcedRebootMinutes : Delay used by forced reboot task path.
.PARAMETER InstalledSomething
When set to True, reboot decisions may consider install outcomes.
.PARAMETER WuaRequestsReboot
When set to True, reboot decisions may mark reboot as needed.
.PARAMETER RebootPendingAtStart
Pending reboot state captured before installation activity.
.PARAMETER AllUpdateResults
Per-update result objects used for failure and rerun signals.
.PARAMETER Reboot
When set, reboot may be initiated when the plan marks reboot as needed;
otherwise a reboot request is not initiated unless RebootAnyway is set.
.PARAMETER RebootAnyway
When set, the plan marks reboot initiation regardless of need.
.PARAMETER XXX_ResumeAfterReboot
Internal continuation marker included in the plan object.
#>
function Get-WuRebootPlan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][bool]$InstalledSomething,
[Parameter(Mandatory=$true)][bool]$WuaRequestsReboot,
[Parameter(Mandatory=$true)][bool]$RebootPendingAtStart,
[Parameter()][AllowNull()][object[]]$AllUpdateResults,
[switch]$Reboot,
[switch]$RebootAnyway,
[switch]$XXX_ResumeAfterReboot
)
$RebootPendingAtEnd=Test-RebootPending
$rebootIsNeeded=$InstalledSomething -and ($WuaRequestsReboot -or $RebootPendingAtEnd)
$failedOrErrorResults=@();$successfulResults=@()
if($AllUpdateResults -and $AllUpdateResults.Count -gt 0){
$failedOrErrorResults=$AllUpdateResults | Where-Object { $_.ResultCode -in @('Failed','SucceededWithErrors') }
$successfulResults=$AllUpdateResults | Where-Object { $_.ResultCode -eq 'Succeeded' }
}
$has80240030=$false
if($AllUpdateResults -and $AllUpdateResults.Count -gt 0){
$has80240030=(($AllUpdateResults | Where-Object { $_.HResult -eq '0x80240030' } | Measure-Object).Count -gt 0)
}
$hasFailures=(@($failedOrErrorResults)).Count -gt 0
$hasSuccesses=(@($successfulResults)).Count -gt 0
$bestToRerunAfterReboot=$has80240030 -or (
$InstalledSomething -and $hasSuccesses -and $hasFailures -and (
((-not $RebootPendingAtStart) -and $RebootPendingAtEnd) -or $WuaRequestsReboot
)
)
$initiateReboot=$false
if($RebootAnyway){ $initiateReboot=$true }
else { $initiateReboot=($rebootIsNeeded -and ($Reboot -or $RebootAnyway)) }
[pscustomobject]@{
RebootPendingAtStart=[bool]$RebootPendingAtStart
RebootPendingAtEnd=[bool]$RebootPendingAtEnd
InstalledSomething=[bool]$InstalledSomething
WuaRequestsReboot=[bool]$WuaRequestsReboot
RebootIsNeeded=[bool]$rebootIsNeeded
InitiateReboot=[bool]$initiateReboot
RebootAnyway=[bool]$RebootAnyway
XXX_ResumeAfterReboot=[bool]$XXX_ResumeAfterReboot
BestToRerunAfterReboot=[bool]$bestToRerunAfterReboot
Has80240030=[bool]$has80240030
HasFailures=[bool]$hasFailures
HasSuccesses=[bool]$hasSuccesses
FailedOrErrorResults=$failedOrErrorResults
AllUpdateResultsCount=(@($AllUpdateResults)).Count
ShutdownDelaySeconds=60
ForcedRebootMinutes=5
}
}
<#
.SYNOPSIS
Applies a reboot plan and performs related user-visible actions.
.DESCRIPTION
Writes decision details to the host, may register continuation state for a
post-reboot rerun, and may schedule a forced reboot task.
When the plan requests reboot initiation, the function issues a reboot
request and may not return before process termination. If continuation or
forced reboot registration fails, the function continues and instructs the
user to rerun after reboot when needed.
.OUTPUTS
None.
#>
function Invoke-WuApplyRebootPlan {
[CmdletBinding()]
param([Parameter(Mandatory=$true)]$Plan,[Parameter()][AllowNull()][string]$ScriptPath,[Parameter(Mandatory=$true)][string]$FlagFilePath)
$askUserToReRun=$false
if($Plan.InitiateReboot -and $Plan.BestToRerunAfterReboot){
if($Plan.XXX_ResumeAfterReboot){
Write-Host -ForegroundColor Yellow "WARNING: We probably need to rerun after the reboot but we already did once. We will NOT rerun a 2nd time."
$askUserToReRun=$true
} elseif(-not $ScriptPath){
Write-Host -ForegroundColor Red "ERROR: We probably need to rerun after the reboot but ScriptPath is not valid (maybe you dot-sourced this script?)"
$askUserToReRun=$true
} else {
Write-Host "Scheduling a continuation of installations after the reboot" -ForegroundColor Magenta
$ok=Register-WuResumeAfterRebootTask -ScriptPath $ScriptPath -FlagFilePath $FlagFilePath
if(-not $ok){ $askUserToReRun=$true }
}
}
Write-Host "Done." -ForegroundColor Cyan
# ---- Raw state / inputs to decision (facts) ----
Write-Host " [Policy] -RebootAnyway: $($Plan.RebootAnyway)" -ForegroundColor DarkGray
Write-Host " [Policy] -XXX_ResumeAfterReboot: $($Plan.XXX_ResumeAfterReboot)" -ForegroundColor DarkGray
Write-Host " [State ] Windows reboot pending at start: $([bool]$Plan.RebootPendingAtStart)" -ForegroundColor DarkGray
Write-Host " [State ] Windows reboot pending now: $([bool]$Plan.RebootPendingAtEnd)" -ForegroundColor DarkGray
Write-Host " [State ] Installer requested reboot now: $([bool]$Plan.WuaRequestsReboot)" -ForegroundColor DarkGray
Write-Host " [Run ] Update result objects produced: $($Plan.AllUpdateResultsCount)" -ForegroundColor Cyan
Write-Host " [Run ] Installed at least one update: $([bool]$Plan.InstalledSomething)" -ForegroundColor Cyan
# ---- Script decision (current logic / policy outcome) ----
Write-Host " [Decide] Script computed RebootIsNeeded: $([bool]$Plan.RebootIsNeeded)" -ForegroundColor Cyan
Write-Host " [Decide] Script will initiate reboot: $([bool]$Plan.InitiateReboot)" -ForegroundColor Cyan
if($Plan.RebootIsNeeded){
Write-Host " [Note ] Current policy says a reboot is needed to finish installations from this run." -ForegroundColor Yellow
} else {
Write-Host " [Note ] Current policy says no reboot is needed to finish installations from this run." -ForegroundColor Green
if($Plan.RebootPendingAtEnd){
Write-Host " [Note ] Windows still reports a pending reboot state (this may be from an earlier operation/run)." -ForegroundColor Yellow
}
if($Plan.RebootAnyway){
Write-Host " [Note ] -RebootAnyway overrides the above and forces a reboot." -ForegroundColor Yellow
}
}
# ---- Extra signals / diagnostics ----
if(( -not $Plan.RebootPendingAtStart) -and $Plan.RebootPendingAtEnd){
Write-Host " [Signal] RebootPending changed from False to True during this run."
}
if($Plan.WuaRequestsReboot){
Write-Host " [Signal] At least one installation reported 'reboot required'."
}
if($Plan.InstalledSomething -and $Plan.HasSuccesses){
Write-Host " [Signal] At least one update installed successfully." -ForegroundColor Green
}
if($Plan.Has80240030){
Write-Host " [Signal] At least one update failed with 0x80240030 (reboot typically required before more installs can continue)." -ForegroundColor Yellow
}
if($Plan.HasFailures){
Write-Host " [Signal] At least one update failed to install." -ForegroundColor Yellow
Write-DbgDump -Json -Label 'failedOrErrorResults' -Obj $Plan.FailedOrErrorResults
}
if($Plan.BestToRerunAfterReboot){
Write-Host " [Advice ] Script suggests running again after reboot." -ForegroundColor Yellow
}
if($askUserToReRun){
Write-Host "*****************************************" -ForegroundColor Magenta
Write-Host "* Please run me again after the reboot. *" -ForegroundColor Magenta
Write-Host "*****************************************" -ForegroundColor Magenta
}
if($Plan.InitiateReboot){
Write-Host "-----------------------" -ForegroundColor Magenta
Write-Host ("REBOOTING in {0} seconds" -f $Plan.ShutdownDelaySeconds) -ForegroundColor Magenta
Write-Host "-----------------------" -ForegroundColor Magenta
Write-Host "To abort, run:"
if($ScriptPath){ Write-Host ('& "'+$ScriptPath+'" -AbortReboot') -ForegroundColor White }
else { Write-Host "shutdown.exe /a" -ForegroundColor White }
if($ScriptPath){
Write-Host ("Scheduling a forced reboot in {0} minutes (just in case the normal reboot request is blocked)." -f $Plan.ForcedRebootMinutes)
[void](Register-WuForcedRebootTask -ScriptPath $ScriptPath -Minutes $Plan.ForcedRebootMinutes -ArmedAt (Get-Date))
} else {
Write-Host -ForegroundColor Yellow "WARNING: Skipping forced reboot safety-net because ScriptPath is not available."
}
if($script:TranscriptEnabled){ try{ Stop-Transcript|Out-Null;$script:TranscriptEnabled=$false }catch{} }
Start-Sleep -Seconds 1
shutdown.exe /r /t $Plan.ShutdownDelaySeconds /c "WindowsUpdatesHelper.ps1: reboot after installing Windows Updates (Not forced)" /d p:0:0
} else {
if($Plan.RebootIsNeeded){
Write-Host "****************************************" -ForegroundColor Magenta
Write-Host "* Please reboot to finish installation *" -ForegroundColor Magenta
Write-Host "****************************************" -ForegroundColor Magenta
}
}
}
# -------------------------------------------------------------------------------------------------
# START
# Function(s) that implememt the mode of operation:
# "History"/"ShowHistory" (where we show windows updates history)
# -------------------------------------------------------------------------------------------------
<#
.SYNOPSIS
Lists Windows Update history entries from the local update history store.
.DESCRIPTION
Returns update history rows after optional date and Defender-definition
filtering.
The scan is limited by MaxScanEntries. Result count is limited by MaxResults
unless MaxResults is 0 or negative.
.OUTPUTS
Produces one psCustomObject per matching history entry:
Date : History entry date/time.
KB : KB number parsed from the title, or empty string.
Title : History entry title text.
Operation : Operation code with text label.
ResultCode : Result code with text label.
HResult : HResult with text description.
.PARAMETER MaxResults
Maximum number of matching rows to return. Use 0 or a negative value to
return all matches found within MaxScanEntries.
.PARAMETER LastDays
When set, only rows on or after now minus this number of days are returned.
.PARAMETER IncludeAV
When set, Defender definition entries are included; otherwise they are
excluded.
.PARAMETER MaxScanEntries
Maximum number of history rows to scan. Must be 1 or greater.
.EXAMPLE
Get-WindowsUpdateHistory -LastDays 14 -MaxResults 100
#>
function Get-WindowsUpdateHistory {
[CmdletBinding()]
param(
[int]$MaxResults = 30,
[int]$LastDays,
[switch]$IncludeAV,
[int]$MaxScanEntries = 10000
)
function _OpText([int]$op) {
switch ($op) {
1 { 'Install' }
2 { 'Uninstall' }
default { 'unknown' }
}
}
if ($MaxScanEntries -lt 1) { throw "MaxScanEntries must be >= 1." }
$cut = $null
if ($PSBoundParameters.ContainsKey('LastDays')) {
$cut = (Get-Date).AddDays(-1 * $LastDays)
}
$batchSize = 100
$start = 0
$scanned = 0
$collected = New-Object System.Collections.Generic.List[object]
$s = New-Object -ComObject Microsoft.Update.Session
$searcher = $s.CreateUpdateSearcher()
while ($scanned -lt $MaxScanEntries) {
$remaining = $MaxScanEntries - $scanned
$take = if ($remaining -lt $batchSize) { $remaining } else { $batchSize }
$batch = $searcher.QueryHistory($start, $take)
if (-not $batch -or $batch.Count -eq 0) { break }
$scanned += $batch.Count
$start += $batch.Count
if ($cut) {
$batch = $batch | Where-Object { $_.Date -ge $cut }
}
if (-not $IncludeAV) {
$batch = $batch | Where-Object { $_.Title -notmatch 'KB2267602' }
}
foreach ($e in $batch) { [void]$collected.Add($e) }
if ($MaxResults -gt 0 -and $collected.Count -ge $MaxResults) { break }
if ($cut) {
$oldestInReturned = ($searcher.QueryHistory($start-1,1) | Select-Object -First 1).Date
if ($oldestInReturned -and $oldestInReturned -lt $cut) { break }
}
if ($batch.Count -lt $take) { break }
}
$final = $collected
if ($MaxResults -gt 0 -and $final.Count -gt $MaxResults) {
$final = $final | Select-Object -First $MaxResults
}
$final | Sort-Object Date | Select-Object `
@{n='Date';e={$_.Date}},
@{n='KB';e={ if ($_.Title -match '(KB\d{5,16})') { $matches[1] } else { '' } }},
@{n='Title';e={$_.Title}},
@{n='Operation';e={ "$($_.Operation)($(_OpText $_.Operation))" }},
@{n='ResultCode';e={ "$($_.ResultCode)($(Get-DescrFromResultCode $_.ResultCode))" }},
@{n='HResult';e={ "$($_.HResult)($(Get-DescrFromHResult $_.HResult))" }}
}
# -------------------------------------------------------------------------------------------------
# END
# Function(s) that implememt the mode of operation:
# "History"/"ShowHistory" (where we show windows updates history)
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# START
# Function(s) that implememt the mode of operation:
# "Logs"/"ListRecentLogs" (where we list log files)
# -------------------------------------------------------------------------------------------------
<#
.SYNOPSIS
Finds this script's transcript log files in known log locations.
.DESCRIPTION
Searches the configured log locations and returns files matching the script
log filename pattern, sorted by LastWriteTime ascending.
Listing failures in one location do not stop listing from other locations.
If no matching files are found, the function writes a host warning.
.OUTPUTS
Produces FileInfo objects sorted by LastWriteTime (oldest to newest).
.PARAMETER RecentCount
Maximum number of files returned when All is not set.
.PARAMETER All
When set, returns all matching files found; otherwise returns only the most
recent RecentCount files.
#>
function Get-WindowsUpdateHelperLogFiles {
param([int]$RecentCount=10,[switch]$All)
$roots=@()
if(Test-Path 'C:\IT\LOG'){ $roots+='C:\IT\LOG' }
if(Test-Path 'C:\IT\LOGS'){ $roots+='C:\IT\LOGS' }
$tmp=[System.IO.Path]::GetTempPath().TrimEnd('\')
if(Test-Path $tmp){ $roots+=$tmp }
$files=@()
foreach($r in $roots){
try {
$files += Get-ChildItem -LiteralPath $r -Filter 'WindowsUpdateHelper-*.log' -File -ErrorAction Stop
} catch {
Write-Host -ForegroundColor Yellow ("WARNING: Could not list log files in '{0}': {1}" -f $r, $_.Exception.Message)
}
}
$files = $files | Sort-Object LastWriteTime
if(-not $All){ $files = $files | Select-Object -Last $RecentCount }
if(-not $files -or $files.Count -eq 0){ Write-Host -ForegroundColor Yellow "No WindowsUpdateHelper log files found in: $($roots -join ', ')" }
$files
}
# -------------------------------------------------------------------------------------------------
# END
# Function(s) that implememt the mode of operation:
# "Logs"/"ListRecentLogs" (where we list log files)
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# START
# Function(s) that implememts -InstallOptional
# -------------------------------------------------------------------------------------------------
<#
.SYNOPSIS
Downloads and installs one update selected by update identifier.
.DESCRIPTION
Searches for applicable updates, locates the requested update ID, downloads
it when needed, and installs it.
The function performs update installation work and writes status lines to the
host. A terminating error can occur after partial progress, including cases
where the target update was downloaded but not installed.
.OUTPUTS
None.
.PARAMETER UpdateId
Identifier of the target update to install. Braced and unbraced GUID text is
accepted.
.PARAMETER Interactive
When set, installation may present prompts; otherwise quiet installation is
requested.
.PARAMETER IncludeNonOptional
When set, the search also includes non-optional updates; otherwise only
optional updates are considered.
.EXAMPLE
Invoke-WuInstallOptionalByUpdateId -UpdateId $id -Interactive
#>
function Invoke-WuInstallOptionalByUpdateId {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$UpdateId,
[switch]$Interactive,
[switch]$IncludeNonOptional
)
function _NormGuid([string]$s){
if(-not $s){ return '' }
$t=$s.Trim()
if($t.StartsWith('{') -and $t.EndsWith('}')){ $t=$t.Substring(1,$t.Length-2) }
$t.ToLowerInvariant()
}
function _TryReleaseCom($o){ if($null -eq $o){return}; try{[void][Runtime.InteropServices.Marshal]::ReleaseComObject($o)}catch{} }
Assert-Elevated
$want=_NormGuid $UpdateId
$session=$null;$searcher=$null;$results=$null
$downloader=$null;$installer=$null
try{
$session=New-Object -ComObject Microsoft.Update.Session
$searcher=$session.CreateUpdateSearcher()
$searcher.Online=$true
$searcher.ServerSelection=2 # ssWindowsUpdate
$base="IsInstalled=0 and IsHidden=0"
$criteria=if($IncludeNonOptional){
"$base and (DeploymentAction='OptionalInstallation' or DeploymentAction='Installation')"
} else {
"$base and DeploymentAction='OptionalInstallation'"
}
Write-Host ("$(Get-Date) Searching WU with criteria: {0}" -f $criteria)
$results=$searcher.Search($criteria)
if(-not $results -or $results.Updates.Count -lt 1){
throw "No matching updates returned by WUA for that criteria."
}
$uMatch=$null
for($i=0;$i -lt $results.Updates.Count;$i++){
$u=$results.Updates.Item($i)
$id=_NormGuid ([string]$u.Identity.UpdateID)
if($id -eq $want){ $uMatch=$u; break }
}
if(-not $uMatch){
$avail=@()
for($i=0;$i -lt $results.Updates.Count;$i++){
$u=$results.Updates.Item($i)
$avail += ("- {0} {1}" -f $u.Title,([string]$u.Identity.UpdateID))
}
throw ("UpdateID not found among returned updates.`nAvailable:`n{0}" -f ($avail -join "`n"))
}
Write-Host ("$(Get-Date) Found update: {0}" -f $uMatch.Title)
if ($uMatch.InstallationBehavior.CanRequestUserInput) {
Write-Host "`nThe installation may need your feedback. Be available.`n" -ForegroundColor Magenta
}
if(-not $uMatch.EulaAccepted){
try{ $uMatch.AcceptEula() } catch { throw ("AcceptEULA failed: {0}" -f $_.Exception.Message) }
}
if(-not $uMatch.IsDownloaded){
Write-Host "$(Get-Date) Downloading..."
$dlColl=New-Object -ComObject Microsoft.Update.UpdateColl
[void]$dlColl.Add($uMatch)
$downloader=$session.CreateUpdateDownloader()
$downloader.Priority=3
$downloader.Updates=$dlColl
$dr=$downloader.Download()
$ur=$dr.GetUpdateResult(0)
if(-not $uMatch.IsDownloaded){
throw ("Download did not result in IsDownloaded=True. ResultCode={0} HResult=0x{1:X8}" -f $dr.ResultCode, $ur.HResult)
}
} else {
Write-Host "Already downloaded." -ForegroundColor DarkGray
}
$instColl=New-Object -ComObject Microsoft.Update.UpdateColl
[void]$instColl.Add($uMatch)
$installer=$session.CreateUpdateInstaller()
$installer.Updates=$instColl
$installer.ForceQuiet = (-not $Interactive)
$installer.AllowSourcePrompts = [bool]$Interactive
Write-Host "$(Get-Date) Installing..."
$ir=$installer.Install()
$one=$ir.GetUpdateResult(0)
$obj=[pscustomobject]@{
Title = $uMatch.Title
UpdateID = [string]$uMatch.Identity.UpdateID
ResultCode = [int]$ir.ResultCode
HResult = ('0x{0:X8}' -f $one.HResult)
RebootRequired = [bool]$ir.RebootRequired -or [bool]$one.RebootRequired
}
Write-Host "ResultCode = $($obj.ResultCode)($(Get-DescrFromResultCode $obj.ResultCode))"
Write-Host "HResult = $($obj.HResult)($(Get-DescrFromHResult $obj.HResult))"
if($obj.RebootRequired){
Write-Host "****************************************" -ForegroundColor Magenta
Write-Host "* Please reboot to finish installation *" -ForegroundColor Magenta
Write-Host "****************************************" -ForegroundColor Magenta
}
# return $obj
}
finally{
_TryReleaseCom $installer
_TryReleaseCom $downloader
_TryReleaseCom $results
_TryReleaseCom $searcher
_TryReleaseCom $session
}
}
# -------------------------------------------------------------------------------------------------
# END
# Function(s) that implememts -InstallOptional
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# START
# Function(s) that implememt the NORMAL mode of operation
# (where we install updates)
# -------------------------------------------------------------------------------------------------
function Format-WuResultCodeName([int]$code){
switch ($code) {
0 {'NotStarted'}
1 {'InProgress'}
2 {'Succeeded'}
3 {'SucceededWithErrors'}
4 {'Failed'}
5 {'Aborted'}