-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsUpdate-Manager.ps1
More file actions
2946 lines (2418 loc) · 88.5 KB
/
WindowsUpdate-Manager.ps1
File metadata and controls
2946 lines (2418 loc) · 88.5 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
Professional Windows Update Manager - Enhanced visual experience with ASCII art, color, and interactive menus.
.DESCRIPTION
WindowsUpdate-Manager v3 is an enhanced, production-ready PowerShell script that provides
a professional, menu-driven console interface for Windows Update management with stunning visuals. Features include:
Core Features (from v2):
- Automated dependency checking and installation (PSWindowsUpdate, NuGet, PowerShell 7.5+)
- Enhanced self-elevation with visual indicators
- Comprehensive error handling and logging
- Pre-flight system checks (disk space, connectivity, services)
- System restore point creation before updates
- KB exclusion lists
- Update categorization (Security, Critical, Optional, Drivers)
- Compliance reporting and audit trails
NEW in v3 - Visual Enhancements:
- ASCII art title with multiple styles (Standard, Slant, Cyberpunk)
- Color gradients and 24-bit RGB support (PS7+)
- Sound effects for key actions
- Responsive layout that adapts to console size
- Enhanced box-drawing characters for professional borders
- Advanced status displays with visual indicators
Update Operations:
- View system status, reboot requirements, and last results
- Scan for updates (Windows Update or Microsoft Update)
- Install all updates or select specific updates
- Hide/unhide updates with persistent exclusion lists
- Uninstall updates by KB number
- View and export update history
- Reset Windows Update components
- Remote installation via Invoke-WUJob (SYSTEM scheduled task)
Configuration:
- Persistent JSON configuration with validation
- Visual settings (animations, sounds, themes)
- Profile import/export
- First-run wizard
- Customizable logging options
.NOTES
File Name : WindowsUpdate-Manager_v3.ps1
Author : Ghostwheel
Version : 3.0.0
Created : 2026-01-19
Last Modified : 2026-01-19
Requirements:
- Windows PowerShell 5.1+ or PowerShell 7.x (7.5+ recommended for best visuals)
- Administrator privileges (script will auto-elevate)
- PSWindowsUpdate module (will auto-install if missing)
- NuGet provider (will auto-install if missing)
- Terminal with ANSI escape sequence support (Windows Terminal, PS7+)
Links:
- PSWindowsUpdate: https://www.powershellgallery.com/packages/PSWindowsUpdate
- GitHub: https://github.com/mgajda83/PSWindowsUpdate
License:
This script is provided "as-is" without warranty. Use at your own risk.
.PARAMETER NoElevation
Prevents automatic elevation to Administrator privileges. Use only if running pre-elevated
or in constrained environments.
.PARAMETER ConfigPath
Path to store configuration settings (JSON format).
Default: $env:APPDATA\WindowsUpdateManager\config.json
.PARAMETER LogPath
Path for transcript logging. If blank, logging is disabled by default but can be enabled
via the settings menu.
.PARAMETER SkipDependencyCheck
Skips automatic dependency checking and installation. Use only if dependencies are
already confirmed to be installed.
.PARAMETER Silent
Minimizes prompts for fully automated operation. Use with caution.
.EXAMPLE
.\WindowsUpdate-Manager_v3.ps1
Runs the script with default settings and auto-elevation.
.EXAMPLE
.\WindowsUpdate-Manager_v3.ps1 -NoElevation -ConfigPath "C:\Config\wu.json"
Runs without elevation using a custom configuration file path.
.EXAMPLE
.\WindowsUpdate-Manager_v3.ps1 -LogPath "C:\Logs\WU.log"
Runs with logging enabled to a specific path.
#>
[CmdletBinding()]
param(
[Parameter(HelpMessage="Prevent automatic elevation")]
[switch]$NoElevation,
[Parameter(HelpMessage="Path to configuration file")]
[ValidateNotNullOrEmpty()]
[string]$ConfigPath = (Join-Path $env:APPDATA "WindowsUpdateManager\config.json"),
[Parameter(HelpMessage="Path for transcript logging")]
[string]$LogPath = "",
[Parameter(HelpMessage="Skip dependency checks")]
[switch]$SkipDependencyCheck,
[Parameter(HelpMessage="Minimize user prompts")]
[switch]$Silent
)
#region Script Variables
$script:Version = "3.0.0"
$script:TranscriptOn = $false
$script:LastScan = @()
$script:LastScanRaw = @()
$script:Config = $null
$script:IsElevated = $false
$script:ErrorLogPath = ""
$script:EscapeChar = [char]27
$script:SupportsANSI = $false
$script:ConsoleDimensions = @{Width=80; Height=24}
#endregion
#region ASCII Art & Visuals
# ASCII Art Titles
$script:AsciiArtTitles = @{
"Standard" = @"
_ _ _ _ _ _ _ _
| | | (_) | | | | | | | | | |
| | | |_ _ __ __| | _____ _____ | | | |_ __ __| | __ _| |_ ___
| |/\| | | '_ \ / _` |/ _ \ \ /\ / / __| | | | | '_ \ / _` |/ _` | __/ _ \
\ /\ / | | | | (_| | (_) \ V V /\__ \ | |_| | |_) | (_| | (_| | || __/
\/ \/|_|_| |_|\__,_|\___/ \_/\_/ |___/ \___/| .__/ \__,_|\__,_|\__\___|
| |
|_|
╔╦╗┌─┐┌┐┌┌─┐┌─┐┌─┐┬─┐
║║║├─┤│││├─┤│ ┬├┤ ├┬┘
╩ ╩┴ ┴┘└┘┴ ┴└─┘└─┘┴└─
"@
"Slant" = @"
_ ___ __ __ __ __ __
| | / (_)___ ____/ /___ _ _____ / / / /___ ____/ /___ _/ /____
| | /| / / / __ \/ __ / __ \ | /| / / __| / / / / __ \/ __ / __ `/ __/ _ \
| |/ |/ / / / / / /_/ / /_/ / |/ |/ /\__ \ / /_/ / /_/ / /_/ / /_/ / /_/ __/
|__/|__/_/_/ /_/\__,_/\____/|__/|__//___/ \____/ .___/\__,_/\__,_/\__/\___/
/_/
╔╦╗┌─┐┌┐┌┌─┐┌─┐┌─┐┬─┐
║║║├─┤│││├─┤│ ┬├┤ ├┬┘
╩ ╩┴ ┴┘└┘┴ ┴└─┘└─┘┴└─
"@
"Cyberpunk" = @"
╦ ╦┬┌┐┌┌┬┐┌─┐┬ ┬┌─┐ ╦ ╦┌─┐┌┬┐┌─┐┌┬┐┌─┐
║║║││││ │││ ││││└─┐ ║ ║├─┘ ││├─┤ │ ├┤
╚╩╝┴┘└┘─┴┘└─┘└┴┘└─┘ ╚═╝┴ ─┴┘┴ ┴ ┴ └─┘
╔╦╗┌─┐┌┐┌┌─┐┌─┐┌─┐┬─┐
║║║├─┤│││├─┤│ ┬├┤ ├┬┘
╩ ╩┴ ┴┘└┘┴ ┴└─┘└─┘┴└─
"@
}
function Get-ConsoleSize {
try {
$width = $Host.UI.RawUI.WindowSize.Width
$height = $Host.UI.RawUI.WindowSize.Height
if ($width -lt 1) { $width = 80 }
if ($height -lt 1) { $height = 24 }
return @{Width = $width; Height = $height}
} catch {
return @{Width = 80; Height = 24}
}
}
function Set-OptimalWindowSize {
param(
[int]$RequiredWidth = 0,
[int]$RequiredHeight = 0
)
<#
.SYNOPSIS
Auto-sizes the console window to fit the menu content optimally.
#>
try {
# Skip if running in ISE or unsupported host
if ($Host.Name -match "ISE" -or -not $Host.UI.RawUI) {
$script:ConsoleDimensions = Get-ConsoleSize
return
}
$raw = $Host.UI.RawUI
# Optimal dimensions for the menu (width for descriptors, height for all options)
$optimalWidth = if ($RequiredWidth -gt 0) { $RequiredWidth } else { 110 }
$optimalHeight = if ($RequiredHeight -gt 0) { $RequiredHeight } else { 40 }
$optimalWidth = [Math]::Max($optimalWidth, 80)
$optimalHeight = [Math]::Max($optimalHeight, 24)
$currentSize = $raw.WindowSize
$maxSize = $raw.MaxPhysicalWindowSize
$maxWidth = if ($maxSize.Width -gt 0) { $maxSize.Width } else { $currentSize.Width }
$maxHeight = if ($maxSize.Height -gt 0) { $maxSize.Height } else { $currentSize.Height }
# Calculate desired size (capped by max)
$newWidth = [Math]::Min($optimalWidth, $maxWidth)
$newHeight = [Math]::Min($optimalHeight, $maxHeight)
# Expand buffer size first (must be >= window size)
$bufferSize = $raw.BufferSize
$targetBufferWidth = [Math]::Max($bufferSize.Width, $newWidth)
$targetBufferHeight = [Math]::Max($bufferSize.Height, $newHeight)
$bufferSize.Width = $targetBufferWidth
$bufferSize.Height = $targetBufferHeight
try { $raw.BufferSize = $bufferSize } catch { }
# Clamp to actual buffer size if the resize was rejected
$bufferSize = $raw.BufferSize
$newWidth = [Math]::Min($newWidth, $bufferSize.Width)
$newHeight = [Math]::Min($newHeight, $bufferSize.Height)
# Only resize if needed and possible
if ($currentSize.Width -ne $newWidth -or $currentSize.Height -ne $newHeight) {
$windowSize = $raw.WindowSize
$windowSize.Width = $newWidth
$windowSize.Height = $newHeight
try {
$raw.WindowSize = $windowSize
} catch {
try { [Console]::SetWindowSize($newWidth, $newHeight) } catch { }
}
}
# Expand buffer height for scrollback if supported
try {
$bufferSize = $raw.BufferSize
if ($bufferSize.Height -lt 3000) {
$bufferSize.Height = 3000
$raw.BufferSize = $bufferSize
}
} catch { }
# Center the window on screen if possible
try {
$windowPos = $raw.WindowPosition
$windowPos.X = [Math]::Max(0, ($maxWidth - $newWidth) / 2)
$windowPos.Y = [Math]::Max(0, ($maxHeight - $newHeight) / 2)
$raw.WindowPosition = $windowPos
} catch {
# Centering might fail in some hosts, ignore
}
# Update script dimensions
$script:ConsoleDimensions = Get-ConsoleSize
} catch {
$script:ConsoleDimensions = Get-ConsoleSize
}
}
function Write-GradientText {
param(
[Parameter(Mandatory)]
[string]$Text,
[int]$StartR = 0, [int]$StartG = 255, [int]$StartB = 255,
[int]$EndR = 0, [int]$EndG = 100, [int]$EndB = 255
)
# Check if gradients are enabled and supported
if (-not $script:Config.Visual.EnableGradients -or -not $script:SupportsANSI) {
Write-Host $Text -ForegroundColor Cyan
return
}
# PowerShell 7+ supports 24-bit RGB
if ($PSVersionTable.PSVersion.Major -ge 7) {
$length = $Text.Length
if ($length -le 1) {
Write-Host $Text
return
}
for ($i = 0; $i -lt $length; $i++) {
$ratio = $i / ($length - 1)
$r = [int]($StartR + ($EndR - $StartR) * $ratio)
$g = [int]($StartG + ($EndG - $StartG) * $ratio)
$b = [int]($StartB + ($EndB - $StartB) * $ratio)
Write-Host "$script:EscapeChar[38;2;$r;$g;${b}m$($Text[$i])" -NoNewline
}
Write-Host "$script:EscapeChar[0m"
} else {
# Fallback for PowerShell 5.1
Write-Host $Text -ForegroundColor Cyan
}
}
function Write-RainbowText {
param(
[Parameter(Mandatory)]
[string]$Text
)
if (-not $script:Config.Visual.EnableGradients -or -not $script:SupportsANSI) {
Write-Host $Text -ForegroundColor Cyan
return
}
if ($PSVersionTable.PSVersion.Major -ge 7) {
$colors = @(
@{R=255; G=0; B=0}, # Red
@{R=255; G=127; B=0}, # Orange
@{R=255; G=255; B=0}, # Yellow
@{R=0; G=255; B=0}, # Green
@{R=0; G=0; B=255}, # Blue
@{R=75; G=0; B=130}, # Indigo
@{R=148; G=0; B=211} # Violet
)
$length = $Text.Length
for ($i = 0; $i -lt $length; $i++) {
$colorIndex = [int](($i / $length) * ($colors.Count - 1))
$c = $colors[$colorIndex]
Write-Host "$script:EscapeChar[38;2;$($c.R);$($c.G);$($c.B)m$($Text[$i])" -NoNewline
}
Write-Host "$script:EscapeChar[0m"
} else {
Write-Host $Text -ForegroundColor Cyan
}
}
function Play-Sound {
param(
[ValidateSet("Startup","Success","Error","Warning","Complete","Click")]
[string]$SoundType
)
if (-not $script:Config.Sounds.$SoundType) {
return
}
try {
switch ($SoundType) {
"Startup" {
[console]::beep(523,100)
[console]::beep(659,100)
[console]::beep(784,150)
}
"Success" {
[console]::beep(784,100)
[console]::beep(1047,200)
}
"Error" {
[console]::beep(400,200)
[console]::beep(300,300)
}
"Warning" {
[console]::beep(600,200)
}
"Complete" {
[console]::beep(523,100)
[console]::beep(659,100)
[console]::beep(784,100)
[console]::beep(1047,300)
}
"Click" {
[console]::beep(800,50)
}
}
} catch {
# Silently fail if beep not supported
}
}
function Show-AsciiTitle {
param([string]$Style = "Standard")
$title = $script:AsciiArtTitles[$Style]
if (-not $title) { $Style = "Standard"; $title = $script:AsciiArtTitles[$Style] }
if ($script:Config.Visual.EnableGradients -and $PSVersionTable.PSVersion.Major -ge 7) {
foreach ($line in ($title -split "`n")) {
Write-GradientText -Text $line -StartR 0 -StartG 255 -StartB 255 -EndR 0 -EndG 150 -EndB 255
}
} else {
Write-Host $title -ForegroundColor Cyan
}
}
function New-BoxBorder {
param(
[Parameter(Mandatory)]
[string]$Content,
[string]$Title = "",
[ValidateSet("Single","Double","Heavy","Rounded","ASCII")]
[string]$Style = "Double",
[int]$Width = 80,
[ConsoleColor]$Color = 'Cyan'
)
# Box drawing character sets
$borders = @{
"Single" = @{TL='┌'; TR='┐'; BL='└'; BR='┘'; H='─'; V='│'; TJ='┬'; BJ='┴'; LJ='├'; RJ='┤'; CJ='┼'}
"Double" = @{TL='╔'; TR='╗'; BL='╚'; BR='╝'; H='═'; V='║'; TJ='╦'; BJ='╩'; LJ='╠'; RJ='╣'; CJ='╬'}
"Heavy" = @{TL='┏'; TR='┓'; BL='┗'; BR='┛'; H='━'; V='┃'; TJ='┳'; BJ='┻'; LJ='┣'; RJ='┫'; CJ='╋'}
"Rounded" = @{TL='╭'; TR='╮'; BL='╰'; BR='╯'; H='─'; V='│'; TJ='┬'; BJ='┴'; LJ='├'; RJ='┤'; CJ='┼'}
"ASCII" = @{TL='+'; TR='+'; BL='+'; BR='+'; H='-'; V='|'; TJ='+'; BJ='+'; LJ='+'; RJ='+'; CJ='+'}
}
$b = $borders[$Style]
$innerWidth = $Width - 2
# Top border
$topBorder = $b.TL + ($b.H * $innerWidth) + $b.TR
Write-Host $topBorder -ForegroundColor $Color
# Title line if provided
if ($Title) {
$titleLen = $Title.Length
$padding = $innerWidth - $titleLen - 2
$leftPad = [Math]::Floor($padding / 2)
$rightPad = $padding - $leftPad
$titleLine = $b.V + (' ' * $leftPad) + $Title + (' ' * $rightPad) + $b.V
Write-Host $titleLine -ForegroundColor $Color
# Separator
$separator = $b.LJ + ($b.H * $innerWidth) + $b.RJ
Write-Host $separator -ForegroundColor $Color
}
# Content lines
$contentLines = $Content -split "`n"
foreach ($line in $contentLines) {
$linelen = $line.Length
$pad = $innerWidth - $linelen
if ($pad -lt 0) {
# Truncate if too long
$line = $line.Substring(0, $innerWidth)
$pad = 0
}
$contentLine = $b.V + $line + (' ' * $pad) + $b.V
Write-Host $contentLine -ForegroundColor $Color
}
# Bottom border
$bottomBorder = $b.BL + ($b.H * $innerWidth) + $b.BR
Write-Host $bottomBorder -ForegroundColor $Color
}
function Show-ProgressBarEnhanced {
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter(Mandatory)]
[string]$Status,
[int]$PercentComplete = 0,
[int]$Total = 100,
[int]$Current = 0,
[string]$Speed = "",
[string]$ETA = ""
)
# Use standard Write-Progress if animations disabled
if (-not $script:Config.Visual.EnableAnimations) {
Write-Progress -Activity $Activity -Status $Status -PercentComplete $PercentComplete
return
}
$size = Get-ConsoleSize
$barWidth = [Math]::Min(50, $size.Width - 40)
$completed = [Math]::Floor($barWidth * $PercentComplete / 100)
$remaining = $barWidth - $completed
$bar = '█' * $completed + '░' * $remaining
Write-Host ""
Write-ColorOutput -Message "┌$('─' * ($barWidth + 30))┐" -ForegroundColor Cyan
Write-Host "│ " -NoNewline -ForegroundColor Cyan
Write-ColorOutput -Message $Activity -ForegroundColor White -NoNewline
Write-Host (' ' * ($barWidth + 28 - $Activity.Length)) -NoNewline
Write-Host "│" -ForegroundColor Cyan
Write-Host "├$('─' * ($barWidth + 30))┤" -ForegroundColor Cyan
Write-Host "│ " -NoNewline -ForegroundColor Cyan
Write-ColorOutput -Message $Status -ForegroundColor Gray -NoNewline
Write-Host (' ' * ($barWidth + 28 - $Status.Length)) -NoNewline
Write-Host "│" -ForegroundColor Cyan
Write-Host "│ " -NoNewline -ForegroundColor Cyan
if ($PercentComplete -ge 75) {
Write-Host $bar -NoNewline -ForegroundColor Green
} elseif ($PercentComplete -ge 50) {
Write-Host $bar -NoNewline -ForegroundColor Yellow
} else {
Write-Host $bar -NoNewline -ForegroundColor Cyan
}
Write-Host " $PercentComplete%" -NoNewline
Write-Host (' ' * ($barWidth + 24 - $bar.Length - $PercentComplete.ToString().Length)) -NoNewline
Write-Host "│" -ForegroundColor Cyan
if ($Speed -or $ETA) {
Write-Host "│ " -NoNewline -ForegroundColor Cyan
$info = ""
if ($Speed) { $info += "⚡ $Speed " }
if ($ETA) { $info += "⏱ ETA: $ETA" }
Write-ColorOutput -Message $info -ForegroundColor Gray -NoNewline
Write-Host (' ' * ($barWidth + 28 - $info.Length)) -NoNewline
Write-Host "│" -ForegroundColor Cyan
}
Write-Host "└$('─' * ($barWidth + 30))┘" -ForegroundColor Cyan
}
#endregion
#region Console & UI Helpers (from v2, enhanced)
function Initialize-Colors {
# Enable VT100 escape sequences for color support (Windows 10+)
try {
# Check ANSI support
$script:SupportsANSI = $false
if ($PSVersionTable.PSVersion.Major -ge 7) {
$script:SupportsANSI = $true
} elseif ($PSVersionTable.BuildVersion.Build -ge 10586) {
$script:SupportsANSI = $true
}
if ($script:SupportsANSI) {
$null = [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
}
} catch {
$script:SupportsANSI = $false
}
# Update console dimensions
$script:ConsoleDimensions = Get-ConsoleSize
}
function Write-Header {
param(
[Parameter(Mandatory)]
[string]$Title,
[Parameter(Mandatory)]
[object]$Config
)
Clear-Host
$line = "=" * $script:ConsoleDimensions.Width
Write-ColorOutput -Message $line -ForegroundColor Cyan
Write-ColorOutput -Message " $Title" -ForegroundColor Cyan -Bold
Write-ColorOutput -Message " Version: $($script:Version)" -ForegroundColor Gray
Write-ColorOutput -Message $line -ForegroundColor Cyan
$computerDisplay = if ($Config.TargetComputers -and $Config.TargetComputers.Count -gt 0) {
$Config.TargetComputers -join ", "
} else {
"LOCAL"
}
$sourceDisplay = if ($Config.UseMicrosoftUpdate) { "Microsoft Update" } else { "Windows Update" }
Write-Host (" Computer(s): {0}" -f $computerDisplay)
Write-Host (" Source : {0}" -f $sourceDisplay)
Write-Host (" AutoReboot : {0} IgnoreReboot: {1} Verbose: {2}" -f $Config.AutoReboot, $Config.IgnoreReboot, $Config.Verbose)
Write-Host (" Logging : {0}" -f $(if ($script:TranscriptOn) { "ON" } else { "OFF" }))
if ($script:IsElevated) {
Write-ColorOutput -Message " Status : Running as Administrator ✓" -ForegroundColor Green
} else {
Write-ColorOutput -Message " Status : Not elevated (some operations may fail)" -ForegroundColor Yellow
}
Write-ColorOutput -Message $line -ForegroundColor Cyan
}
function Write-ColorOutput {
param(
[Parameter(Mandatory)]
[string]$Message,
[Parameter()]
[ConsoleColor]$ForegroundColor = [ConsoleColor]::White,
[Parameter()]
[ConsoleColor]$BackgroundColor,
[Parameter()]
[switch]$Bold,
[Parameter()]
[switch]$NoNewline
)
$params = @{
Object = $Message
ForegroundColor = $ForegroundColor
}
if ($BackgroundColor) {
$params.BackgroundColor = $BackgroundColor
}
if ($NoNewline) {
$params.NoNewline = $true
}
Write-Host @params
}
function Write-Info {
param([Parameter(Mandatory)][string]$Message)
Write-ColorOutput -Message ("[ℹ] {0}" -f $Message) -ForegroundColor Cyan
}
function Write-Ok {
param([Parameter(Mandatory)][string]$Message)
Write-ColorOutput -Message ("[✓] {0}" -f $Message) -ForegroundColor Green
}
function Write-Warn {
param([Parameter(Mandatory)][string]$Message)
Write-ColorOutput -Message ("[⚠] {0}" -f $Message) -ForegroundColor Yellow
}
function Write-Err {
param([Parameter(Mandatory)][string]$Message)
Write-ColorOutput -Message ("[✗] {0}" -f $Message) -ForegroundColor Red
Write-ErrorLog -Message $Message
if ($script:Config.Sounds.Error) {
Play-Sound -SoundType "Error"
}
}
function Write-Success {
param([Parameter(Mandatory)][string]$Message)
Write-ColorOutput -Message ("[✓] {0}" -f $Message) -ForegroundColor Green
if ($script:Config.Sounds.Success) {
Play-Sound -SoundType "Success"
}
}
function Write-Progress-Enhanced {
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter(Mandatory)]
[string]$Status,
[Parameter()]
[int]$PercentComplete = -1
)
if ($PercentComplete -ge 0) {
Write-Progress -Activity $Activity -Status $Status -PercentComplete $PercentComplete
} else {
Write-Progress -Activity $Activity -Status $Status
}
}
function Pause-UI {
param([string]$Message = "Press Enter to continue...")
Write-Host ""
[void](Read-Host $Message)
}
function Read-YesNo {
param(
[Parameter(Mandatory)]
[string]$Prompt,
[switch]$DefaultYes
)
if ($Silent) { return [bool]$DefaultYes }
$suffix = if ($DefaultYes) { " [Y/n]" } else { " [y/N]" }
$answer = Read-Host ($Prompt + $suffix)
if ([string]::IsNullOrWhiteSpace($answer)) {
return [bool]$DefaultYes
}
return ($answer.Trim().ToLowerInvariant() -in @("y","yes"))
}
function Show-Banner {
Clear-Host
# Play startup sound
Play-Sound -SoundType "Startup"
# Show ASCII art title
$style = $script:Config.Visual.AsciiArtStyle
if (-not $style) { $style = "Cyberpunk" }
Show-AsciiTitle -Style $style
Write-Host ""
Write-ColorOutput -Message " Professional Update Management Tool" -ForegroundColor Gray
Write-ColorOutput -Message " Version $($script:Version)" -ForegroundColor Gray
Write-Host ""
}
#endregion
#region Error Logging (unchanged from v2)
function Initialize-ErrorLog {
try {
$logDir = Join-Path $env:APPDATA "WindowsUpdateManager\logs"
if (-not (Test-Path $logDir)) {
New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}
$script:ErrorLogPath = Join-Path $logDir ("ErrorLog_{0}.txt" -f (Get-Date -Format "yyyyMMdd_HHmmss"))
Add-Content -Path $script:ErrorLogPath -Value ("=" * 80) -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value "Windows Update Manager v$($script:Version) - Error Log" -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value ("Started: {0}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss")) -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value ("=" * 80) -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value "" -ErrorAction SilentlyContinue
} catch {
# Silent fail on log initialization
}
}
function Write-ErrorLog {
param(
[Parameter(Mandatory)]
[string]$Message,
[Parameter()]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
try {
if ([string]::IsNullOrEmpty($script:ErrorLogPath)) { return }
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[{0}] {1}" -f $timestamp, $Message
Add-Content -Path $script:ErrorLogPath -Value $logEntry -ErrorAction SilentlyContinue
if ($ErrorRecord) {
Add-Content -Path $script:ErrorLogPath -Value (" Exception: {0}" -f $ErrorRecord.Exception.Message) -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value (" Category : {0}" -f $ErrorRecord.CategoryInfo.Category) -ErrorAction SilentlyContinue
Add-Content -Path $script:ErrorLogPath -Value "" -ErrorAction SilentlyContinue
}
} catch {
# Silent fail on error logging
}
}
#endregion
#region Admin & Environment (unchanged from v2)
function Test-IsAdmin {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
} catch {
Write-ErrorLog -Message "Failed to check admin status" -ErrorRecord $_
return $false
}
}
function Ensure-Elevation {
param([switch]$Skip)
if ($Skip) {
Write-Warn "Skipping elevation check. Some operations may fail without admin rights."
return
}
if (Test-IsAdmin) {
$script:IsElevated = $true
return
}
Write-Warn "Administrator privileges required. Attempting to elevate..."
try {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = if ($PSVersionTable.PSVersion.Major -ge 7) { "pwsh.exe" } else { "powershell.exe" }
$args = @(
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", ('"{0}"' -f $PSCommandPath)
)
if ($NoElevation) { $args += "-NoElevation" }
if ($ConfigPath) { $args += @("-ConfigPath", ('"{0}"' -f $ConfigPath)) }
if ($LogPath) { $args += @("-LogPath", ('"{0}"' -f $LogPath)) }
if ($SkipDependencyCheck) { $args += "-SkipDependencyCheck" }
if ($Silent) { $args += "-Silent" }
$psi.Arguments = ($args -join " ")
$psi.Verb = "runas"
$psi.UseShellExecute = $true
$process = [Diagnostics.Process]::Start($psi)
if ($null -ne $process) {
Write-Success "Elevated instance started. This window will close."
Start-Sleep -Seconds 2
exit 0
}
} catch {
Write-Err "Elevation failed or was cancelled."
Write-ErrorLog -Message "Elevation failed" -ErrorRecord $_
Write-Warn "Some operations require administrator rights and may not work."
Start-Sleep -Seconds 3
}
}
function Test-InternetConnectivity {
try {
$result = Test-Connection -ComputerName "8.8.8.8" -Count 1 -Quiet -ErrorAction SilentlyContinue
return $result
} catch {
return $false
}
}
function Get-FreeDiskSpace {
param([string]$Drive = "C:")
try {
$disk = Get-PSDrive -Name $Drive.TrimEnd(':') -ErrorAction Stop
return [math]::Round($disk.Free / 1GB, 2)
} catch {
return 0
}
}
function Test-WindowsUpdateService {
try {
$service = Get-Service -Name "wuauserv" -ErrorAction Stop
return ($service.Status -eq 'Running')
} catch {
return $false
}
}
#endregion
#region Pre-flight Checks (unchanged from v2)
function Invoke-PreFlightChecks {
param([switch]$Detailed)
Write-Info "Running pre-flight system checks..."
$allPassed = $true
# Check 1: Internet connectivity
Write-Host " Checking internet connectivity..." -NoNewline
if (Test-InternetConnectivity) {
Write-ColorOutput -Message " ✓" -ForegroundColor Green
} else {
Write-ColorOutput -Message " ✗" -ForegroundColor Red
Write-Warn "No internet connectivity detected. Update operations will fail."
$allPassed = $false
}
# Check 2: Disk space
Write-Host " Checking disk space..." -NoNewline
$freeSpace = Get-FreeDiskSpace -Drive "C:"
if ($freeSpace -gt 10) {
Write-ColorOutput -Message (" ✓ ({0:N2} GB free)" -f $freeSpace) -ForegroundColor Green
} elseif ($freeSpace -gt 5) {
Write-ColorOutput -Message (" ⚠ ({0:N2} GB free - Low)" -f $freeSpace) -ForegroundColor Yellow
} else {
Write-ColorOutput -Message (" ✗ ({0:N2} GB free - Critical)" -f $freeSpace) -ForegroundColor Red
Write-Warn "Insufficient disk space. At least 10GB recommended for updates."
$allPassed = $false
}
# Check 3: Windows Update service
Write-Host " Checking Windows Update service..." -NoNewline
if (Test-WindowsUpdateService) {
Write-ColorOutput -Message " ✓" -ForegroundColor Green
} else {
Write-ColorOutput -Message " ⚠" -ForegroundColor Yellow
Write-Warn "Windows Update service is not running. Attempting to start..."
try {
Start-Service -Name "wuauserv" -ErrorAction Stop
Write-Success "Windows Update service started successfully."
} catch {
Write-Err "Failed to start Windows Update service."
$allPassed = $false
}
}
# Check 4: PowerShell version
if ($Detailed) {
Write-Host " PowerShell version..." -NoNewline
$psVersion = $PSVersionTable.PSVersion
if ($psVersion.Major -ge 7 -and $psVersion.Minor -ge 5) {
Write-ColorOutput -Message (" ✓ ({0})" -f $psVersion) -ForegroundColor Green
} elseif ($psVersion.Major -ge 5) {
Write-ColorOutput -Message (" ⚠ ({0} - Consider upgrading)" -f $psVersion) -ForegroundColor Yellow
} else {
Write-ColorOutput -Message (" ✗ ({0} - Unsupported)" -f $psVersion) -ForegroundColor Red
$allPassed = $false
}
}
Write-Host ""
if ($allPassed) {
Write-Success "All pre-flight checks passed."
} else {
Write-Warn "Some pre-flight checks failed. Proceed with caution."
}
return $allPassed
}
#endregion
#region Dependency Management (unchanged from v2)
function Test-NuGetProvider {
try {
$nuget = Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue
return ($null -ne $nuget)
} catch {
return $false
}
}
function Install-NuGetProvider {
Write-Info "Installing NuGet package provider..."
try {
# Ensure TLS 1.2 for PowerShell Gallery
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction Stop | Out-Null
Write-Success "NuGet provider installed successfully."
return $true
} catch {
Write-Err "Failed to install NuGet provider: $($_.Exception.Message)"
Write-ErrorLog -Message "NuGet installation failed" -ErrorRecord $_
return $false
}
}
function Get-InstalledPowerShellVersion {
return $PSVersionTable.PSVersion
}
function Test-PowerShell7Available {
try {
$ps7Path = if ($env:ProgramFiles) {
Join-Path $env:ProgramFiles "PowerShell\7\pwsh.exe"
} else {
$null
}
if ($ps7Path -and (Test-Path $ps7Path)) {
return $true
}
$pwsh = Get-Command pwsh.exe -ErrorAction SilentlyContinue