Repository navigation
Expand file tree
/
Copy pathWindowsUpdatesHelper.ps1
More file actions
2556 lines (2186 loc) · 111 KB
/
Copy pathWindowsUpdatesHelper.ps1
File metadata and controls
2556 lines (2186 loc) · 111 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
Lists pending Windows Updates, installs updates, or shows update history using the WUA COM API.
.DESCRIPTION
Three main modes. Choose one per invocation:
1. STATUS: view pending updates without changing them.
-Status Offline lists only updates already downloaded, using cached information.
-Status Online scans the configured update source and lists both downloaded
updates and updates available for download. Neither downloads update payloads,
installs updates, or reboots.
2. INSTALL: use -Install to install pending updates already downloaded.
Add -Download to scan online, download missing updates, and then install them.
For compatibility, -Download and -Reboot imply -Install.
-Reboot, -RebootAnyway, and -RebootAt control whether and when to reboot.
-InstallOptional <UpdateID> installs one optional update by ID.
3. HISTORY: view past update activity.
-ShowHistory lists recorded update operations and their results, including
failed attempts. It does not list pending updates, download, install, or reboot.
-ListRecentLogs and -AbortReboot are separate log and reboot-management commands.
With no arguments, the script prints a short usage message and exits.
Detailed arguments and usage examples follow.
.PARAMETER Status
List pending updates and exit. Offline uses cached update information and lists
only updates already downloaded. Online scans the configured Windows Update
source (including WSUS when configured) and lists downloaded and undownloaded
updates. The online scan retrieves metadata, not update payloads.
Both modes include optional and interactive updates, excluding installed or
hidden updates. Output objects contain Downloaded, KB, Title, and UpdateID.
Cannot be combined with installation, reboot, history, or log options.
.PARAMETER Install
Install eligible pending updates already downloaded. Add -Download to download
missing updates first. -Download and -Reboot imply -Install for compatibility;
-RebootAnyway, -RebootAt, and internal continuation runs also select installation.
With no installation request, the script prints usage and exits.
.PARAMETER Download
Implies -Install. Perform online scan and download applicable updates that are not yet downloaded, then proceed to install everything downloaded.
.PARAMETER Reboot
Implies -Install. After installation, reboot only if updates require it
(or regardless if -RebootAnyway is also used).
.PARAMETER RebootAt
Implies -Reboot. After installation, schedules one reboot at the next matching
local date and time, only if needed (or regardless with -RebootAnyway).
Syntax: 'HH:mm', optionally followed by WeekDay or MonthDay comparisons joined
with 'and', for example '06:14 and WeekDay=Sunday and MonthDay>14'.
WeekDay supports = and <> with English day names. MonthDay (1-31) supports
=, <>, <, <=, >, >=. Hour and Hour24 are not supported here.
Nonexistent local times during a DST change are skipped; ambiguous local times
use the standard-time occurrence.
The scheduled task issues `shutdown /r /t 60` so it starts the reboot about one
minute later. A missed scheduled minute is skipped without catch-up or retry.
The reboot will be performed even when an intervening manual reboot occurred.
If after the reboot further installation is needed, continuation runs may request
additional reboots independently of the original schedule for up to ONE HOUR after
the initial scheduled time. This deadline is never extended by continuation runs.
Continuation state is only created when requesting a reboot, not while scheduling
it days in advance.
Use -AbortReboot to cancel the future task and any continuation state too.
.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).
Still subject to -RebootAt when supplied.
.PARAMETER AbortReboot
Abort a reboot initiated by this script and cancel its future reboot and continuation tasks.
.PARAMETER InstallOptional
Installs an optional update (needs the update ID)
.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).
.EXAMPLE
# List already downloaded pending updates without installing them:
.\WindowsUpdatesHelper.ps1 -Status Offline
.EXAMPLE
# Scan online and list pending updates with their download state:
.\WindowsUpdatesHelper.ps1 -Status Online
.EXAMPLE
# Install any already downloaded updates and reboot if needed:
.\WindowsUpdatesHelper.ps1 -Install -Reboot
.EXAMPLE
# Download, Install and if needed reboot:
.\WindowsUpdatesHelper.ps1 -Install -Download -Reboot
.EXAMPLE
# Compatibility: -Download and -Reboot imply -Install:
.\WindowsUpdatesHelper.ps1 -Download -Reboot
.EXAMPLE
# Compatibility: -Download alone downloads and installs:
.\WindowsUpdatesHelper.ps1 -Download
.EXAMPLE
# Download, Install and reboot regardless of whether updates require it:
.\WindowsUpdatesHelper.ps1 -Install -Download -Reboot -RebootAnyway
.EXAMPLE
.\WindowsUpdatesHelper.ps1 -Install -Download -RebootAt "06:14"
.EXAMPLE
.\WindowsUpdatesHelper.ps1 -Install -Download -RebootAt "06:14 and WeekDay=Sunday and MonthDay>14"
.EXAMPLE
# Show latest Windows Update history entries:
.\WindowsUpdatesHelper.ps1 -ShowHistory
.EXAMPLE
# Show latest Windows Update history entries, include AV updates:
.\WindowsUpdatesHelper.ps1 -ShowHistory -LastDays 14 -IncludeAV
.EXAMPLE
# List the most recent 10 log files created by this script (most recent last):
.\WindowsUpdatesHelper.ps1 -ListRecentLogs
.EXAMPLE
The fastest way to bring a new installation up-to-date:
**CAUTION**: WILL REBOOT WITHOUT WAITING / WITHOUT ASKING
```
# Download & first run
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force
$p="C:\it\bin";mkdir $p -force >$null
$f="WindowsUpdatesHelper.ps1";iwr -useb https://wiki.enlogic.gr/pub/KnowledgeBase/PublicFiles/$f -OutFile $p\$f
& C:\it\bin\WindowsUpdatesHelper.ps1 -Install -Download -Reboot
# 2nd Run (REPEAT UNTIL YOU GET 0 Updates Found)
& c:\it\bin\WindowsUpdatesHelper.ps1 -Install -Download -Reboot -Interactive
# It will also install updates that MAY ask you to accept EULAs or make choices
```
.EXAMPLE
# Display the logs from the last 10 executions of this script
& c:\it\bin\WindowsUpdatesHelper.ps1 -ListRecentLogs | %{cat $_.fullname|sls -NotMatch '^(Machine|Host Application|Process ID|Log file|Configuration Name|Username|End time|[A-Z][a-z]*(Versions?|Edition)): '}
.EXAMPLE
**CAUTION**: An unfortunate side-effect of this script is that the updates
it installs are not visible in the GUI (Settings -> Windows Updates).
The only way to view them:
```
& c:\it\bin\WindowsUpdatesHelper.ps1 -ShowHistory | ft
# You may add -IncludeAV if you want to also view (the very frequent) Antivirus udpates
```
---
.PARAMETER XXX_ResumeAfterReboot
DO NOT USE THIS SWITCH. It is used INTERNALLY to continue installations after a reboot.
.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 XXX_ScheduledRebootAt
INTERNAL: the chosen instant for a one-shot -RebootAt task.
.PARAMETER XXX_ContinueAfterReboot
INTERNAL: prepare continuation only when the scheduled reboot is requested.
.PARAMETER XXX_RebootAtUntil
INTERNAL: the original, fixed one-hour deadline for -RebootAt continuations.
.NOTES
## Regarding 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).
- The 60-second shutdown countdown implies /f. Immediate -Reboot mode
retains a second attempt after five minutes; -RebootAt has no forced fallback.
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.
#>
<#
=== 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]$Install,
[Parameter(ParameterSetName='Install')][switch]$Download,
[Parameter(ParameterSetName='Install')][switch]$Reboot,
[Parameter(ParameterSetName='Install')][switch]$RebootAnyway,
[Parameter(ParameterSetName='Install')][AllowEmptyString()][string]$RebootAt,
[Parameter(ParameterSetName='Install')][datetimeoffset]$XXX_RebootAtUntil = [datetimeoffset]::MinValue,
[Parameter(ParameterSetName='Install')][Alias('CanRequestUserInput')][switch]$Interactive,
[Parameter(ParameterSetName='Install')][switch]$XXX_ResumeAfterReboot,
[Parameter(ParameterSetName='Status', Mandatory=$true)][ValidateSet('Offline','Online')][string]$Status,
[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='Special')][datetimeoffset]$XXX_ScheduledRebootAt = [datetimeoffset]::MinValue,
[Parameter(ParameterSetName='Special')][switch]$XXX_ContinueAfterReboot,
[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 Get-WuPendingUpdateStatus {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][ValidateSet('Offline','Online')][string]$Mode)
$session = New-Object -ComObject 'Microsoft.Update.Session' -ErrorAction Stop
$searcher = $session.CreateUpdateSearcher()
$searcher.Online = ($Mode -eq 'Online')
$searcher.CanAutomaticallyUpgradeService = $false
$criteria = "(IsInstalled=0 and IsHidden=0 and DeploymentAction='Installation') or (IsInstalled=0 and IsHidden=0 and DeploymentAction='OptionalInstallation')"
$result = $searcher.Search($criteria)
if ([int]$result.ResultCode -ne 2) {
throw "Windows Update status search did not complete successfully (ResultCode=$($result.ResultCode))."
}
$count = 0
for ($i = 0; $i -lt $result.Updates.Count; $i++) {
$update = $result.Updates.Item($i)
if ($Mode -eq 'Offline' -and -not $update.IsDownloaded) { continue }
$count++
[pscustomobject]@{
Downloaded = [bool]$update.IsDownloaded
KB = (@($update.KBArticleIDs) -join ', ')
Title = [string]$update.Title
UpdateID = [string]$update.Identity.UpdateID
}
}
Write-Host ("Found {0} pending update(s) ({1})." -f $count, $Mode)
}
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
Validates and evaluates the date conditions in a reboot schedule.
#>
function Test-WuRebootDateCondition {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][AllowEmptyString()][string]$Condition,
[datetime]$At = (Get-Date)
)
if ([string]::IsNullOrWhiteSpace($Condition)) { throw "-RebootAt must not be empty." }
$isMatch = $true
foreach ($clause in [regex]::Split($Condition.Trim(), '(?i)\s+and\s+')) {
if ($clause -notmatch '^\s*(WeekDay|MonthDay)\s*(<>|<=|>=|=|<|>)\s*([A-Za-z]+|[0-9]+)\s*$') {
throw "Invalid -RebootAt clause '$clause'. Use supported comparisons joined with 'and'."
}
$field = $Matches[1]
$operator = $Matches[2]
$value = $Matches[3]
if ($field -eq 'WeekDay') {
if ($operator -notin @('=', '<>') -or $value -notin [enum]::GetNames([DayOfWeek])) {
throw "Invalid -RebootAt clause '$clause'. WeekDay requires = or <> and an English day name."
}
$actual = [int]$At.DayOfWeek
$expected = [int][enum]::Parse([DayOfWeek], $value, $true)
} else {
$actual = $At.Day
$expected = 0
if (-not [int]::TryParse($value, [ref]$expected) -or $expected -lt 1 -or $expected -gt 31) {
throw "Invalid -RebootAt clause '$clause'. MonthDay requires a number from 1 to 31."
}
}
$clauseMatches = switch ($operator) {
'=' { $actual -eq $expected }
'<>' { $actual -ne $expected }
'<' { $actual -lt $expected }
'<=' { $actual -le $expected }
'>' { $actual -gt $expected }
'>=' { $actual -ge $expected }
}
# Evaluate every clause so an earlier false comparison cannot hide a typo.
$isMatch = $isMatch -and $clauseMatches
}
return $isMatch
}
<#
.SYNOPSIS
Finds the next matching local reboot time; rejects impossible date conditions.
#>
function Get-WuRebootTime {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][AllowEmptyString()][string]$Schedule, [datetime]$After = (Get-Date))
$clauses = [regex]::Split($Schedule.Trim(), '(?i)\s+and\s+')
if ($clauses[0] -notmatch '^([01][0-9]|2[0-3]):([0-5][0-9])$') {
throw '-RebootAt must start with a 24-hour time in HH:mm format.'
}
$time = [timespan]::FromMinutes(([int]$Matches[1] * 60) + [int]$Matches[2])
$dateClauses = @($clauses | Select-Object -Skip 1)
if ($dateClauses.Count) { [void](Test-WuRebootDateCondition -Condition ($dateClauses -join ' and ')) }
# Date fields are independent. Reuse the comparison evaluator to intersect
# each field's possible values and reject contradictions before searching.
$weekCondition = (@($dateClauses | Where-Object { $_ -match '^\s*WeekDay\b' }) -join ' and ')
$monthCondition = (@($dateClauses | Where-Object { $_ -match '^\s*MonthDay\b' }) -join ' and ')
$weekDays = @(0..6 | Where-Object { -not $weekCondition -or (Test-WuRebootDateCondition -Condition $weekCondition -At ([datetime]'2023-01-01').AddDays($_)) })
$monthDays = @(1..31 | Where-Object { -not $monthCondition -or (Test-WuRebootDateCondition -Condition $monthCondition -At ([datetime]'2023-01-01').AddDays($_ - 1)) })
if (-not $weekDays.Count -or -not $monthDays.Count) { throw '-RebootAt date conditions cannot be satisfied.' }
# Gregorian weekdays/dates repeat every 400 years; this is a complete bound.
for ($day = $After.Date; $day -lt $After.Date.AddYears(400); $day = $day.AddDays(1)) {
$candidate = [datetime]::SpecifyKind($day.Add($time), [DateTimeKind]::Unspecified)
if ([int]$candidate.DayOfWeek -notin $weekDays -or $candidate.Day -notin $monthDays) { continue }
if ([TimeZoneInfo]::Local.IsInvalidTime($candidate)) { continue }
if ($candidate.ToUniversalTime() -le $After.ToUniversalTime()) { continue }
return $candidate
}
throw '-RebootAt has no future matching date.'
}
<#
.SYNOPSIS
Estimates the UTC boot time from native 64-bit uptime, without WMI.
.NOTES
Uptime includes sleep and hibernation. Wall-clock corrections can shift the
estimated boot timestamp because it is calculated from the current UTC time.
#>
function Get-WuSystemBootTimeUtc {
[CmdletBinding()]
param()
if (-not ('WindowsUpdateHelperBootClock' -as [type])) {
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
public static class WindowsUpdateHelperBootClock {
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern ulong GetTickCount64();
}
'@ -ErrorAction Stop
}
$uptimeMilliseconds = [WindowsUpdateHelperBootClock]::GetTickCount64()
[datetime]::UtcNow.AddMilliseconds(-[double]$uptimeMilliseconds)
}
<#
.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
)
if (-not $script:WuDebugOutputEnabled) { return }
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([switch]$EmitStatus)
$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
if ($EmitStatus) { 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
if ($EmitStatus) { 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.ToUniversalTime().ToString('o',[Globalization.CultureInfo]::InvariantCulture)
$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,[datetimeoffset]$RebootAtUntil = [datetimeoffset]::MinValue)
$taskName='WindowsUpdateHelper-ResumeAfterReboot'
# The deadline argument alone carries -RebootAt continuation state.
$okFlag=($RebootAtUntil -ne [datetimeoffset]::MinValue);$okTask=$false
if(-not $okFlag){
try{
$now=Get-Date
Set-Content -LiteralPath $FlagFilePath -Value $now.ToString('s') -Encoding ASCII -Force
Write-Host ("[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'
if($RebootAtUntil -ne [datetimeoffset]::MinValue){ $argLine+=' -XXX_RebootAtUntil "'+$RebootAtUntil.ToString('o',[Globalization.CultureInfo]::InvariantCulture)+'"' }
$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 -ErrorAction Stop | Out-Null
Write-Host ("[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
Registers a single future reboot without creating startup continuation state.
#>
function Register-WuScheduledRebootTask {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ScriptPath,[Parameter(Mandatory=$true)][datetime]$At,[switch]$ContinueAfterReboot)
$dueUtc=$At.ToUniversalTime()
$psExe=Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$arguments='-NoLogo -NoProfile -ExecutionPolicy Bypass -File "'+$ScriptPath+'" -XXX_ScheduledRebootAt "'+$dueUtc.ToString('o',[Globalization.CultureInfo]::InvariantCulture)+'"'
if($ContinueAfterReboot){ $arguments+=' -XXX_ContinueAfterReboot' }
$action=New-ScheduledTaskAction -Execute $psExe -Argument $arguments
$trigger=New-ScheduledTaskTrigger -Once -At $At
# Pin the chosen instant across DST and enforce a single scheduled minute.
$trigger.StartBoundary=$dueUtc.ToString('yyyy-MM-ddTHH:mm:ssZ')
$trigger.EndBoundary=$dueUtc.AddMinutes(1).ToString('yyyy-MM-ddTHH:mm:ssZ')
$settings=New-ScheduledTaskSettingsSet -StartWhenAvailable:$false -DeleteExpiredTaskAfter (New-TimeSpan -Hours 1) -ExecutionTimeLimit (New-TimeSpan -Minutes 5)
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName 'WindowsUpdateHelper-ScheduledReboot' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force -ErrorAction Stop | Out-Null
Write-Host ("[RebootAt] Scheduled one reboot request for {0} local time ({1} UTC). Reboot normally starts 60 seconds later. No catch-up or forced fallback." -f $At.ToString('yyyy-MM-dd HH:mm:ss'),$dueUtc.ToString('yyyy-MM-dd HH:mm:ss'))
}
<#
.SYNOPSIS
Requests a scheduled/continuation restart within the original one-hour deadline.
#>
function Invoke-WuScheduledRestart {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ScriptPath,[Parameter(Mandatory=$true)][string]$FlagFilePath,[Parameter(Mandatory=$true)][datetimeoffset]$Until,[switch]$ContinueAfterReboot,[datetimeoffset]$RequestBefore = [datetimeoffset]::MaxValue)
$nowUtc=(Get-Date).ToUniversalTime()
if($nowUtc.AddSeconds(60) -gt $Until.UtcDateTime -or $nowUtc -ge $RequestBefore.UtcDateTime){
Write-Host -ForegroundColor Yellow '[RebootAt] Skipping reboot: outside the permitted request time or the countdown would exceed the one-hour deadline.'
return
}
$registered=$false
$requested=$false
try {
if($ContinueAfterReboot){
$registered=Register-WuResumeAfterRebootTask -ScriptPath $ScriptPath -FlagFilePath $FlagFilePath -RebootAtUntil $Until
if(-not $registered){ Write-Host -ForegroundColor Yellow '[RebootAt] Could not prepare continuation; rerun manually after reboot if needed.' }
}
$nowUtc=(Get-Date).ToUniversalTime()
if($nowUtc.AddSeconds(60) -gt $Until.UtcDateTime -or $nowUtc -ge $RequestBefore.UtcDateTime){
Write-Host -ForegroundColor Yellow '[RebootAt] Skipping reboot: permitted request time expired while preparing continuation.'
return
}
Write-Host ("[RebootAt] Requesting reboot in 60 seconds. Continuation deadline: {0} local time. Use -AbortReboot to cancel." -f $Until.LocalDateTime.ToString('yyyy-MM-dd HH:mm:ss'))
shutdown.exe /r /t 60 /c "WindowsUpdatesHelper.ps1: scheduled Windows Update reboot" /d p:0:0
if($LASTEXITCODE -ne 0){ throw "[RebootAt] shutdown.exe failed with exit code $LASTEXITCODE. No retry is scheduled." }
$requested=$true
} finally {
if($registered -and -not $requested){
try { Unregister-ScheduledTask -TaskName 'WindowsUpdateHelper-ResumeAfterReboot' -Confirm:$false -ErrorAction Stop | Out-Null }
catch { Write-Host -ForegroundColor Yellow ("[RebootAt] WARNING: Could not remove prepared continuation task: {0}" -f $_.Exception.Message) }
}
}
}
<#
.SYNOPSIS
Executes a scheduled request only during its chosen minute, with no boot check.
#>
function Invoke-WuScheduledReboot {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][datetimeoffset]$At,[Parameter(Mandatory=$true)][string]$ScriptPath,[Parameter(Mandatory=$true)][string]$FlagFilePath,[switch]$ContinueAfterReboot)
$nowUtc=(Get-Date).ToUniversalTime()
if($nowUtc -lt $At.UtcDateTime -or $nowUtc -ge $At.UtcDateTime.AddMinutes(1)){
Write-Host -ForegroundColor Yellow ("[RebootAt] Skipping reboot: outside the scheduled minute {0}. No catch-up or retry." -f $At.LocalDateTime.ToString('yyyy-MM-dd HH:mm'))
return
}
# The scheduled reboot remains valid even after an intervening manual reboot.
Invoke-WuScheduledRestart -ScriptPath $ScriptPath -FlagFilePath $FlagFilePath -Until $At.AddHours(1) -ContinueAfterReboot:$ContinueAfterReboot -RequestBefore $At.AddMinutes(1)
}
<#
.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.
RebootAt : Schedule used to select one future reboot time.
RebootAtUntil : Fixed deadline for scheduled-reboot continuations.
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,
[string]$RebootAt,
[datetimeoffset]$RebootAtUntil = [datetimeoffset]::MinValue,
[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 [bool]$RebootAt -or $RebootAtUntil -ne [datetimeoffset]::MinValue)) }
[pscustomobject]@{
RebootPendingAtStart=[bool]$RebootPendingAtStart
RebootPendingAtEnd=[bool]$RebootPendingAtEnd
InstalledSomething=[bool]$InstalledSomething
WuaRequestsReboot=[bool]$WuaRequestsReboot
RebootIsNeeded=[bool]$rebootIsNeeded
InitiateReboot=[bool]$initiateReboot
RebootAnyway=[bool]$RebootAnyway
RebootAt=$RebootAt
RebootAtUntil=$RebootAtUntil
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)
# Scheduled reboots and their continuations never use the legacy fallback.
if($Plan.RebootAt -or $Plan.RebootAtUntil -ne [datetimeoffset]::MinValue){
if(-not $Plan.InitiateReboot){ Write-Host '[RebootAt] No reboot needed; no task was created.'; return }
if(-not $ScriptPath){ throw '[RebootAt] A script file path is required to schedule reboot/continuation.' }
if($Plan.RebootAtUntil -ne [datetimeoffset]::MinValue){
Invoke-WuScheduledRestart -ScriptPath $ScriptPath -FlagFilePath $FlagFilePath -Until $Plan.RebootAtUntil -ContinueAfterReboot:$Plan.BestToRerunAfterReboot
} else {
$at=Get-WuRebootTime -Schedule $Plan.RebootAt
Register-WuScheduledRebootTask -ScriptPath $ScriptPath -At $at -ContinueAfterReboot:$Plan.BestToRerunAfterReboot
}
return
}
$askUserToReRun=$false
$continuationRegistered=$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
$continuationRegistered=Register-WuResumeAfterRebootTask -ScriptPath $ScriptPath -FlagFilePath $FlagFilePath
if(-not $continuationRegistered){ $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 ignores reboot necessity." -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)
$null=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."
}
Start-Sleep -Seconds 1
if($script:TranscriptEnabled){ try{ Stop-Transcript|Out-Null;$script:TranscriptEnabled=$false }catch{} }
shutdown.exe /r /t $Plan.ShutdownDelaySeconds /c "WindowsUpdatesHelper.ps1: reboot after installing Windows Updates (60-second countdown)" /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