-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinServerSetup.ps1
More file actions
3252 lines (2995 loc) · 159 KB
/
WinServerSetup.ps1
File metadata and controls
3252 lines (2995 loc) · 159 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
# WinServerSetup.ps1
# Main provisioning script for Windows / Windows Server after a clean install.
# Designed to be re-runnable, idempotent, admin-only, and to leave the machine
# in a known good state at the end (with an optional auto-restart).
#
# All CLI text, logs, and inline comments are in English by design.
[CmdletBinding()]
param(
[switch]$Full,
[switch]$NoPause,
[switch]$NoColor,
[switch]$NoReboot,
[switch]$NoRelocate
)
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor `
[Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11
$Global:NoColor = [bool]$NoColor
$Global:NoPause = [bool]$NoPause
$Global:NoReboot = [bool]$NoReboot
$Global:NoRelocate = [bool]$NoRelocate
$Global:Full = [bool]$Full
function Get-ProjectRoot {
if ($PSScriptRoot) { return $PSScriptRoot }
return Split-Path -Parent $MyInvocation.MyCommand.Path
}
$Global:ProjectRoot = Get-ProjectRoot
$Global:ConfigPath = Join-Path $Global:ProjectRoot "WinServerSetup.config.json"
$Global:Config = $null
$Global:ScriptVersion = "1.2.0"
$Global:TranscriptStarted= $false
$Global:LogFile = $null
$Global:StructuredLog = $null
# Summary tracking used by Show-FinalSummary at the end of Full setup.
$Global:RunStats = [pscustomobject]@{
StartedTasks = New-Object System.Collections.Generic.List[string]
CompletedTasks = New-Object System.Collections.Generic.List[string]
FailedTasks = New-Object System.Collections.Generic.List[string]
SkippedTasks = New-Object System.Collections.Generic.List[string]
Warnings = New-Object System.Collections.Generic.List[string]
InstalledApps = New-Object System.Collections.Generic.List[string]
FailedApps = New-Object System.Collections.Generic.List[string]
RebootRequired = $false
}
# =============================================================================
# COLORED TERMINAL OUTPUT
# =============================================================================
# All terminal output goes through Write-Themed or a semantic wrapper. The
# palette can be retuned from $Global:WinServerSetupColors. Color is disabled
# by any of: -NoColor switch, $env:NO_COLOR, $env:WINSERVERSETUP_NOCOLOR.
# We use Write-Host -ForegroundColor (ConsoleColor) so transcripts stay clean.
$Global:WinServerSetupColors = @{
Success = 'Green'
Error = 'Red'
Warning = 'Yellow'
Info = 'Cyan'
Prompt = 'Yellow'
Title = 'Cyan'
TitleRule = 'DarkCyan'
Section = 'Magenta'
Option = ''
OptionNum = 'Cyan'
Status = 'DarkCyan'
Summary = 'Magenta'
SummaryDim = 'DarkGray'
}
function Test-ColorSupported {
if ($Global:NoColor) { return $false }
if (-not [string]::IsNullOrEmpty($env:NO_COLOR)) { return $false }
if (-not [string]::IsNullOrEmpty($env:WINSERVERSETUP_NOCOLOR)) { return $false }
return $true
}
function Set-ColorEnabled {
param([Parameter(Mandatory)][bool]$Enabled)
$Global:NoColor = -not $Enabled
}
function Write-Themed {
param(
[Parameter(Mandatory, Position=0)][AllowEmptyString()][string]$Message,
[ValidateSet('Success','Error','Warning','Info','Prompt','Title','TitleRule','Section','Option','OptionNum','Status','Summary','SummaryDim','Plain')]
[string]$Kind = 'Plain',
[switch]$NoNewline
)
$useColor = (Test-ColorSupported) -and ($Kind -ne 'Plain')
$color = $null
if ($useColor) {
$color = $Global:WinServerSetupColors[$Kind]
if ([string]::IsNullOrEmpty($color)) { $useColor = $false }
}
try {
if ($useColor) {
Write-Host $Message -ForegroundColor $color -NoNewline:$NoNewline
} else {
Write-Host $Message -NoNewline:$NoNewline
}
} catch {
Write-Host $Message -NoNewline:$NoNewline
}
}
function Write-Color {
param([Parameter(Mandatory)][string]$Message, [string]$Color = "White")
if (Test-ColorSupported) {
try { Write-Host $Message -ForegroundColor $Color; return } catch { }
}
Write-Host $Message
}
# Semantic console helpers (also forward to the structured log when active).
function Write-Info { param([string]$Message) Write-Themed "[INFO] $Message" -Kind Info; Write-StructuredLog -Level INFO -Message $Message }
function Write-Ok { param([string]$Message) Write-Themed "[OK] $Message" -Kind Success; Write-StructuredLog -Level OK -Message $Message }
function Write-Warn { param([string]$Message) Write-Themed "[WARN] $Message" -Kind Warning; Write-StructuredLog -Level WARN -Message $Message; $null = $Global:RunStats.Warnings.Add($Message) }
function Write-Fail { param([string]$Message) Write-Themed "[ERROR] $Message" -Kind Error; Write-StructuredLog -Level ERROR -Message $Message }
function Write-Status { param([string]$Message) Write-Themed $Message -Kind Status; Write-StructuredLog -Level STATUS -Message $Message }
function Write-Summary { param([string]$Message) Write-Themed $Message -Kind Summary; Write-StructuredLog -Level SUMMARY -Message $Message }
function Write-Section {
param([Parameter(Mandatory)][string]$Title)
Write-Host ""
Write-Themed ("==== {0} ====" -f $Title) -Kind Section
Write-StructuredLog -Level SECTION -Message $Title
}
function Write-Title {
param([Parameter(Mandatory)][string]$Title)
Write-Themed $Title -Kind Title
}
function Write-Rule {
param([int]$Width = 30, [string]$Char = '=')
Write-Themed ($Char * $Width) -Kind TitleRule
}
function Write-Option {
param([Parameter(Mandatory)][string]$Number, [Parameter(Mandatory)][string]$Label)
Write-Themed ("{0,3}. " -f $Number) -Kind OptionNum -NoNewline
Write-Themed $Label -Kind Option
}
# In-place status line (overwrites previous line, no spinner spam).
function Write-StatusInPlace {
param([Parameter(Mandatory)][string]$Message)
$line = "`r{0,-100}" -f $Message
if (Test-ColorSupported) {
try { Write-Host $line -ForegroundColor $Global:WinServerSetupColors['Status'] -NoNewline; return } catch { }
}
Write-Host $line -NoNewline
}
function Clear-StatusInPlace {
Write-Host ("`r{0,-100}`r" -f " ") -NoNewline
}
# =============================================================================
# STRUCTURED LOGGING (UTF-8)
# =============================================================================
# Two log streams:
# 1) Transcript (Start-Transcript) -> human-readable copy of the console
# 2) Structured log -> machine-friendly: [timestamp] [level] [section] message
# Both are written under logs/ in UTF-8.
function Initialize-StructuredLog {
param([Parameter(Mandatory)][string]$LogDirectory)
if (-not (Test-Path $LogDirectory)) {
New-Item -ItemType Directory -Path $LogDirectory -Force | Out-Null
}
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$Global:StructuredLog = Join-Path $LogDirectory ("WinServerSetup-structured-{0}.log" -f $stamp)
Set-Content -LiteralPath $Global:StructuredLog -Value ("# WinServerSetup {0} structured log started {1}" -f $Global:ScriptVersion, (Get-Date -Format "u")) -Encoding utf8
}
function Write-StructuredLog {
param(
[string]$Level = 'INFO',
[string]$Message = '',
[string]$Section = ''
)
if (-not $Global:StructuredLog) { return }
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = if ($Section) {
"[{0}] [{1,-7}] [{2}] {3}" -f $ts, $Level, $Section, $Message
} else {
"[{0}] [{1,-7}] {2}" -f $ts, $Level, $Message
}
try { Add-Content -LiteralPath $Global:StructuredLog -Value $line -Encoding utf8 } catch { }
}
# =============================================================================
# ACTIVE OPERATION TIMER
# =============================================================================
function Initialize-ActiveTimer {
if (-not $Global:OpStopwatch) { $Global:OpStopwatch = [System.Diagnostics.Stopwatch]::new() }
}
function Start-ActiveTimer { Initialize-ActiveTimer; $Global:OpStopwatch.Reset(); $Global:OpStopwatch.Start() }
function Suspend-ActiveTimer { if ($Global:OpStopwatch -and $Global:OpStopwatch.IsRunning) { $Global:OpStopwatch.Stop() } }
function Resume-ActiveTimer { if ($Global:OpStopwatch -and -not $Global:OpStopwatch.IsRunning -and $Global:OpStopwatch.Elapsed -gt [TimeSpan]::Zero) { $Global:OpStopwatch.Start() } }
function Stop-ActiveTimer { if ($Global:OpStopwatch -and $Global:OpStopwatch.IsRunning) { $Global:OpStopwatch.Stop() } }
function Get-ActiveTimerElapsed { if (-not $Global:OpStopwatch) { return [TimeSpan]::Zero }; return $Global:OpStopwatch.Elapsed }
function Format-ActiveTimerElapsed {
$ts = Get-ActiveTimerElapsed
$hours = [int][Math]::Floor($ts.TotalHours)
return ('{0:00}:{1:00}:{2:00}' -f $hours, $ts.Minutes, $ts.Seconds)
}
function Write-ActiveTimerSummary {
param([string]$Name = "")
$elapsed = Format-ActiveTimerElapsed
if ([string]::IsNullOrWhiteSpace($Name)) {
Write-Summary ("Total time elapsed: {0}" -f $elapsed)
} else {
Write-Summary ("Total time elapsed: {0} ({1})" -f $elapsed, $Name)
}
Write-Themed "(active operation time only; user prompts and menu waits are excluded)" -Kind SummaryDim
}
function Invoke-Timed {
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][scriptblock]$Action)
$null = $Global:RunStats.StartedTasks.Add($Name)
Start-ActiveTimer
try {
& $Action
$null = $Global:RunStats.CompletedTasks.Add($Name)
} catch {
$null = $Global:RunStats.FailedTasks.Add($Name)
Write-Fail ("Task '{0}' failed: {1}" -f $Name, $_.Exception.Message)
throw
} finally {
Stop-ActiveTimer
Write-Host ""
Write-ActiveTimerSummary -Name $Name
}
}
function Invoke-RecordedSetupStep {
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][scriptblock]$Action,
[switch]$PassThru
)
$null = $Global:RunStats.StartedTasks.Add($Name)
Write-StructuredLog -Level TASK -Message ("Started: {0}" -f $Name)
try {
$result = & $Action
$null = $Global:RunStats.CompletedTasks.Add($Name)
Write-StructuredLog -Level TASK -Message ("Completed: {0}" -f $Name)
if ($PassThru) { return $result }
} catch {
$null = $Global:RunStats.FailedTasks.Add($Name)
Write-StructuredLog -Level ERROR -Message ("Failed: {0}; {1}" -f $Name, $_.Exception.Message)
throw
}
}
# =============================================================================
# PRESS-ANY-KEY PROMPTS
# =============================================================================
# Uses [Console]::ReadKey($true) where supported (true any-key). Falls back to
# Read-Host (Enter-only) for non-interactive hosts. Both forms suspend the
# active timer so user-wait time is never counted as work time.
function Read-AnyKeyThemed {
param([string]$Prompt = "Press any key to continue...")
$wasRunning = ($Global:OpStopwatch -and $Global:OpStopwatch.IsRunning)
Suspend-ActiveTimer
try {
Write-Themed $Prompt -Kind Prompt
try {
if ($Host.UI.RawUI -and [Console]::IsInputRedirected -eq $false) {
[void][Console]::ReadKey($true)
return
}
} catch { }
# Fallback for hosts without RawUI:
Read-Host | Out-Null
} finally {
if ($wasRunning) { Resume-ActiveTimer }
}
}
function Read-HostThemed {
param([Parameter(Mandatory)][string]$Prompt)
$wasRunning = ($Global:OpStopwatch -and $Global:OpStopwatch.IsRunning)
Suspend-ActiveTimer
try {
Write-Themed ($Prompt + ": ") -Kind Prompt -NoNewline
return Read-Host
} finally {
if ($wasRunning) { Resume-ActiveTimer }
}
}
function Read-HostUntimed { param([string]$Prompt) Read-HostThemed -Prompt $Prompt }
function Pause-IfNeeded {
if (-not $Global:NoPause) {
Write-Host ""
Read-AnyKeyThemed
}
}
# =============================================================================
# ADMIN / CONFIG / PATH HELPERS
# =============================================================================
function Assert-Admin {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Fail "Run this script as Administrator."
Pause-IfNeeded
exit 1
}
}
function Load-Config {
if (-not (Test-Path $Global:ConfigPath)) {
throw "Config file not found: $Global:ConfigPath"
}
$Global:Config = Get-Content -LiteralPath $Global:ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
}
function Resolve-RelativePath {
param([Parameter(Mandatory)][string]$Path)
if ([System.IO.Path]::IsPathRooted($Path)) { return $Path }
return Join-Path $Global:ProjectRoot $Path
}
function Set-RegistryDefaultValue {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][AllowEmptyString()][string]$Value
)
if (-not (Test-Path $Path)) { New-Item -Path $Path -Force | Out-Null }
(Get-Item -Path $Path).SetValue('', $Value, [Microsoft.Win32.RegistryValueKind]::String)
}
function Get-RegistryDefaultValue {
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path $Path)) { return $null }
return (Get-Item -Path $Path).GetValue('', $null)
}
function Ensure-Directory {
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path $Path)) {
New-Item -ItemType Directory -Path $Path -Force | Out-Null
Write-Ok "Created directory: $Path"
}
}
function Get-DownloadCachePath {
# downloadRoot, if empty, defaults to a per-user temp folder so the script
# never silently creates C:\portable\_downloads. Override via config.
$cfgValue = ''
if ($Global:Config) { $cfgValue = [string]$Global:Config.downloadRoot }
if ([string]::IsNullOrWhiteSpace($cfgValue)) {
$cfgValue = Join-Path $env:TEMP "WinServerSetup-downloads"
}
Ensure-Directory $cfgValue
return $cfgValue
}
function Get-SafeDownloadCacheFilePath {
param([Parameter(Mandatory)][string]$FileName)
$leaf = Split-Path -Leaf $FileName
if ([string]::IsNullOrWhiteSpace($leaf)) {
throw "Download file name is empty."
}
if (-not [string]::Equals($leaf, $FileName, [System.StringComparison]::Ordinal)) {
Write-Warn ("Download file name contained path segments; using safe leaf name: {0}" -f $leaf)
}
$root = [System.IO.Path]::GetFullPath((Get-DownloadCachePath)).TrimEnd('\')
$candidate = [System.IO.Path]::GetFullPath((Join-Path $root $leaf))
if (-not $candidate.StartsWith($root + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Resolved download path is outside the configured cache: $candidate"
}
return $candidate
}
function Test-DownloadedFileSignature {
param([Parameter(Mandatory)][string]$Path)
$ext = [System.IO.Path]::GetExtension($Path).ToLowerInvariant()
if ($ext -notin @('.exe', '.msi', '.msix', '.msixbundle', '.appx', '.appxbundle')) {
Write-StructuredLog -Level SIGNATURE -Message ("Authenticode signature not applicable for file type: {0}" -f $Path)
return $null
}
try {
$sig = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
if ($sig.Status -eq 'Valid') {
Write-StructuredLog -Level SIGNATURE -Message ("Valid signature: {0}; signer={1}" -f $Path, $sig.SignerCertificate.Subject)
return $true
} else {
Write-Warn ("Downloaded file signature is not valid for {0}: {1}. Installer will remain available, but verify the source if this is unexpected." -f (Split-Path -Leaf $Path), $sig.Status)
Write-StructuredLog -Level SIGNATURE -Message ("Non-valid signature: {0}; status={1}; message={2}" -f $Path, $sig.Status, $sig.StatusMessage)
return $false
}
} catch {
Write-Warn ("Could not verify downloaded file signature for {0}: {1}" -f (Split-Path -Leaf $Path), $_.Exception.Message)
return $false
}
}
function Test-FileSha256 {
param(
[Parameter(Mandatory)][string]$Path,
[string]$ExpectedSha256 = ""
)
if ([string]::IsNullOrWhiteSpace($ExpectedSha256)) { return $true }
try {
$actual = (Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash
if ([string]::Equals($actual, $ExpectedSha256.Trim(), [System.StringComparison]::OrdinalIgnoreCase)) {
Write-StructuredLog -Level HASH -Message ("SHA256 verified: {0}" -f $Path)
return $true
}
Write-Warn ("SHA256 mismatch for {0}. Expected {1}, got {2}." -f (Split-Path -Leaf $Path), $ExpectedSha256, $actual)
Write-StructuredLog -Level HASH -Message ("SHA256 mismatch: {0}; expected={1}; actual={2}" -f $Path, $ExpectedSha256, $actual)
return $false
} catch {
Write-Warn ("Could not verify SHA256 for {0}: {1}" -f (Split-Path -Leaf $Path), $_.Exception.Message)
return $false
}
}
function Initialize-Environment {
Load-Config
$logRoot = Resolve-RelativePath ([string]$Global:Config.logRoot)
Ensure-Directory $logRoot
Ensure-Directory (Resolve-RelativePath "backups")
Initialize-StructuredLog -LogDirectory $logRoot
$portableRoot = [string]$Global:Config.portableRoot
if (-not [string]::IsNullOrWhiteSpace($portableRoot)) { Ensure-Directory $portableRoot }
if (-not $Global:TranscriptStarted) {
$Global:LogFile = Join-Path $logRoot ("WinServerSetup-{0}.log" -f (Get-Date -Format "yyyyMMdd-HHmmss"))
try {
Start-Transcript -Path $Global:LogFile -Append -Encoding utf8 -Force | Out-Null
$Global:TranscriptStarted = $true
Write-Info "WinServerSetup version: $Global:ScriptVersion"
Write-Info "Console transcript: $Global:LogFile"
Write-Info "Structured log file: $Global:StructuredLog"
} catch {
Write-Warn "Could not start transcript: $($_.Exception.Message)"
}
}
}
function Test-CommandExists {
param([Parameter(Mandatory)][string]$Command)
return [bool](Get-Command $Command -ErrorAction SilentlyContinue)
}
# =============================================================================
# PENDING REBOOT TRACKER
# =============================================================================
function Set-PendingReboot {
param([string]$Reason = "")
$Global:RunStats.RebootRequired = $true
if (-not [string]::IsNullOrWhiteSpace($Reason)) {
Write-Warn "Pending reboot flagged: $Reason"
} else {
Write-Warn "Pending reboot flagged."
}
}
function Test-WindowsRebootRequired {
$signals = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"
)
foreach ($p in $signals) { if (Test-Path $p) { return $true } }
try {
$pending = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue)
$ops = @($pending.PendingFileRenameOperations | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) })
if ($ops.Count -gt 0) { return $true }
} catch {
Write-StructuredLog -Level DEBUG -Message ("PendingFileRenameOperations check failed: {0}" -f $_.Exception.Message)
}
return $false
}
# =============================================================================
# SELF-RELOCATE
# =============================================================================
# Move the entire project folder to C:\portable\Scripts\WinServerSetup on first
# run. Uses robocopy to preserve everything, then re-launches at the new path
# and exits the current process cleanly.
function Invoke-SelfRelocateIfNeeded {
if ($Global:NoRelocate) {
Write-Info "Self-relocate skipped: -NoRelocate switch is set."
return $false
}
if (-not $Global:Config.selfRelocate -or -not $Global:Config.selfRelocate.enabled) {
Write-Info "Self-relocate skipped: disabled in config."
return $false
}
$target = [string]$Global:Config.targetProjectRoot
if ([string]::IsNullOrWhiteSpace($target)) { $target = "C:\portable\Scripts\WinServerSetup" }
$currentFull = (Resolve-Path -LiteralPath $Global:ProjectRoot).Path.TrimEnd('\')
$targetFull = $target.TrimEnd('\')
if ([string]::Equals($currentFull, $targetFull, [System.StringComparison]::OrdinalIgnoreCase)) {
Write-Info "Project is already running from target location: $target"
return $false
}
Write-Section "Self-relocating project to $target"
$parent = Split-Path -Parent $target
Ensure-Directory $parent
$targetLogDir = Join-Path $targetFull "logs"
$relocateLog = Join-Path $targetLogDir ("WinServerSetup-relocate-{0}.log" -f (Get-Date -Format "yyyyMMdd-HHmmss"))
# Copy with robocopy, then schedule removal of the original source after the
# relaunched target process starts. /E updates/merges without deleting
# unexpected destination files.
Write-Info "Copying files from '$currentFull' to '$targetFull' ..."
$robocopyLog = Join-Path $env:TEMP "WinServerSetup-relocate.log"
$proc = Start-Process robocopy.exe `
-ArgumentList @("`"$currentFull`"", "`"$targetFull`"", "/E", "/COPY:DAT", "/R:1", "/W:2", "/NFL", "/NDL", "/NJH", "/NJS", "/NC", "/NS", "/LOG:`"$robocopyLog`"") `
-Wait -PassThru -WindowStyle Hidden
# robocopy exit codes <=7 are success (8+ are real failures).
if ($proc.ExitCode -ge 8) {
throw "robocopy failed with exit code $($proc.ExitCode). See $robocopyLog"
}
Write-Ok "Project files copied. robocopy exit code $($proc.ExitCode)."
Ensure-Directory $targetLogDir
@(
("[{0}] [INFO] Source: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $currentFull),
("[{0}] [INFO] Target: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $targetFull),
("[{0}] [INFO] robocopy exit code: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $proc.ExitCode),
("[{0}] [INFO] robocopy log: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $robocopyLog)
) | Set-Content -LiteralPath $relocateLog -Encoding utf8
# Relaunch from the new location and exit this process.
$newScript = Join-Path $targetFull "WinServerSetup.ps1"
$childArgs = @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$newScript`"", "-NoRelocate")
if ($Global:Full) { $childArgs += "-Full" }
if ($Global:NoPause) { $childArgs += "-NoPause" }
if ($Global:NoColor) { $childArgs += "-NoColor" }
if ($Global:NoReboot){ $childArgs += "-NoReboot" }
Write-Info ("Relaunching from new location: {0}" -f $newScript)
$relocatedProcess = Start-Process powershell.exe -ArgumentList $childArgs -PassThru
Write-Info ("Relocated setup process started. PID={0}; relocation log={1}" -f $relocatedProcess.Id, $relocateLog)
try {
$cleanupScript = Join-Path $env:TEMP ("WinServerSetup-clean-source-{0}.ps1" -f ([guid]::NewGuid().ToString("N")))
$parentPid = $PID
$cleanup = @"
param(
[Parameter(Mandatory = `$true)][string]`$SourcePath,
[Parameter(Mandatory = `$true)][string]`$TargetPath,
[Parameter(Mandatory = `$true)][int]`$ParentProcessId,
[Parameter(Mandatory = `$true)][string]`$RelocateLog
)
`$ErrorActionPreference = 'SilentlyContinue'
try { Wait-Process -Id `$ParentProcessId -Timeout 60 } catch { Start-Sleep -Seconds 5 }
try {
`$src = [System.IO.Path]::GetFullPath(`$SourcePath).TrimEnd('\')
`$dst = [System.IO.Path]::GetFullPath(`$TargetPath).TrimEnd('\')
if (`$src -and `$dst -and -not [string]::Equals(`$src, `$dst, [System.StringComparison]::OrdinalIgnoreCase) -and -not `$dst.StartsWith(`$src + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath `$src -Recurse -Force -ErrorAction Stop
Add-Content -LiteralPath `$RelocateLog -Encoding utf8 -Value ("[{0}] [OK] Removed original source folder: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), `$src)
}
} catch {
Add-Content -LiteralPath `$RelocateLog -Encoding utf8 -Value ("[{0}] [WARN] Could not remove original source folder: {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), `$_.Exception.Message)
}
try { Remove-Item -LiteralPath `$MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue } catch { }
"@
Set-Content -LiteralPath $cleanupScript -Value $cleanup -Encoding utf8 -Force
Start-Process powershell.exe -WindowStyle Hidden -ArgumentList @(
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$cleanupScript`"",
"-SourcePath", "`"$currentFull`"", "-TargetPath", "`"$targetFull`"",
"-ParentProcessId", "$parentPid", "-RelocateLog", "`"$relocateLog`""
)
Write-Info "Original source folder cleanup scheduled after this process exits."
} catch {
Write-Warn "Could not schedule source cleanup after relocation: $($_.Exception.Message)"
}
Write-Info "Original script will now exit. Future runs should use the new location."
return $true
}
# =============================================================================
# CONTROLLED PARALLEL RUNNER
# =============================================================================
# Runs a set of safe, independent script blocks concurrently with a hard cap on
# how many can be in flight at once. Prefers Start-ThreadJob (lightweight, same
# process) and falls back to Start-Job. Designed for VM-friendly limits.
function Test-ThreadJobAvailable {
if (Get-Command Start-ThreadJob -ErrorAction SilentlyContinue) { return $true }
if (Get-Module -ListAvailable -Name ThreadJob) { return $true }
return $false
}
function Invoke-Parallel {
param(
[Parameter(Mandatory)][array]$Tasks, # each item: @{ Name='...'; Action={ ... } }
[int]$MaxParallel = 2
)
if (-not $Tasks -or $Tasks.Count -eq 0) { return }
if ($MaxParallel -lt 1) { $MaxParallel = 1 }
$useThreadJob = Test-ThreadJobAvailable
if ($useThreadJob -and -not (Get-Command Start-ThreadJob -ErrorAction SilentlyContinue)) {
try { Import-Module ThreadJob -ErrorAction Stop } catch { $useThreadJob = $false }
}
$runnerLabel = if ($useThreadJob) { 'ThreadJob' } else { 'Process Job' }
Write-Info ("Parallel runner: {0} task(s), max {1} concurrent ({2})." -f $Tasks.Count, $MaxParallel, $runnerLabel)
$jobs = @{}
$pending = New-Object System.Collections.Generic.Queue[object]
foreach ($t in $Tasks) { $pending.Enqueue($t) }
while ($pending.Count -gt 0 -or $jobs.Count -gt 0) {
while ($jobs.Count -lt $MaxParallel -and $pending.Count -gt 0) {
$task = $pending.Dequeue()
$name = [string]$task.Name
$sb = [scriptblock]$task.Action
try {
$job = if ($useThreadJob) { Start-ThreadJob -Name $name -ScriptBlock $sb } else { Start-Job -Name $name -ScriptBlock $sb }
$jobs[$job.Id] = @{ Name = $name; Job = $job; Started = Get-Date }
Write-Info ("Parallel start: {0}" -f $name)
} catch {
Write-Fail ("Parallel start failed for {0}: {1}" -f $name, $_.Exception.Message)
$null = $Global:RunStats.FailedTasks.Add("(parallel) $name")
}
}
if ($jobs.Count -eq 0) { break }
$finished = $jobs.Values | Where-Object { $_.Job.State -in @('Completed','Failed','Stopped') } | Select-Object -First 1
if ($finished) {
$j = $finished.Job
$elapsed = (Get-Date) - $finished.Started
try { $output = Receive-Job -Job $j -ErrorAction Stop -Keep } catch { $output = $_.Exception.Message }
if ($j.State -eq 'Completed') {
Write-Ok ("Parallel done : {0} [{1:N1}s]" -f $finished.Name, $elapsed.TotalSeconds)
} else {
Write-Fail ("Parallel fail : {0} [{1:N1}s] {2}" -f $finished.Name, $elapsed.TotalSeconds, ($output -join '; '))
$null = $Global:RunStats.FailedTasks.Add("(parallel) $($finished.Name)")
}
Remove-Job -Job $j -Force -ErrorAction SilentlyContinue | Out-Null
$jobs.Remove($j.Id) | Out-Null
} else {
Start-Sleep -Milliseconds 250
}
}
}
function Start-ParallelTasks {
param(
[Parameter(Mandatory)][array]$Tasks,
[int]$MaxParallel = 2
)
if (-not $Tasks -or $Tasks.Count -eq 0) { return @() }
if ($MaxParallel -lt 1) { $MaxParallel = 1 }
$useThreadJob = Test-ThreadJobAvailable
if ($useThreadJob -and -not (Get-Command Start-ThreadJob -ErrorAction SilentlyContinue)) {
try { Import-Module ThreadJob -ErrorAction Stop } catch { $useThreadJob = $false }
}
$started = New-Object System.Collections.Generic.List[object]
foreach ($task in $Tasks | Select-Object -First $MaxParallel) {
$name = [string]$task.Name
$sb = [scriptblock]$task.Action
try {
$job = if ($useThreadJob) { Start-ThreadJob -Name $name -ScriptBlock $sb } else { Start-Job -Name $name -ScriptBlock $sb }
$started.Add([pscustomobject]@{ Name = $name; Job = $job; Started = Get-Date }) | Out-Null
Write-Info ("Parallel start: {0}" -f $name)
} catch {
Write-Warn ("Parallel start failed for {0}: {1}" -f $name, $_.Exception.Message)
$null = $Global:RunStats.FailedTasks.Add("(parallel) $name")
}
}
return @($started)
}
function Wait-ParallelTasks {
param([array]$StartedTasks)
foreach ($item in @($StartedTasks)) {
if (-not $item -or -not $item.Job) { continue }
$job = $item.Job
try {
Wait-Job -Job $job | Out-Null
$elapsed = (Get-Date) - $item.Started
$output = @()
try { $output = @(Receive-Job -Job $job -ErrorAction SilentlyContinue) } catch { $output = @($_.Exception.Message) }
foreach ($line in $output) {
$text = [string]$line
if (-not [string]::IsNullOrWhiteSpace($text)) {
Write-StructuredLog -Level OUTPUT -Message ("parallel {0}> {1}" -f $item.Name, $text.TrimEnd())
}
}
if ($job.State -eq 'Completed') {
Write-Ok ("Parallel done : {0} [{1:N1}s]" -f $item.Name, $elapsed.TotalSeconds)
$null = $Global:RunStats.CompletedTasks.Add("(parallel) $($item.Name)")
} else {
Write-Warn ("Parallel fail : {0} [{1:N1}s] state={2}" -f $item.Name, $elapsed.TotalSeconds, $job.State)
$null = $Global:RunStats.FailedTasks.Add("(parallel) $($item.Name)")
}
} finally {
Remove-Job -Job $job -Force -ErrorAction SilentlyContinue | Out-Null
}
}
}
function Start-ApplicationDownloadPrefetch {
param([int]$MaxParallel = 4)
$prefetchScript = Join-Path $Global:ProjectRoot "scripts\Prefetch-AppDownloads.ps1"
if (-not (Test-Path $prefetchScript)) {
Write-Warn "Application prefetch helper not found: $prefetchScript"
return $null
}
if ($MaxParallel -lt 1) { $MaxParallel = 1 }
$logRoot = Resolve-RelativePath ([string]$Global:Config.logRoot)
Ensure-Directory $logRoot
$prefetchLog = Join-Path $logRoot ("WinServerSetup-prefetch-{0}.log" -f (Get-Date -Format "yyyyMMdd-HHmmss"))
$psExe = Join-Path $env:windir "System32\WindowsPowerShell\v1.0\powershell.exe"
$prefetchArgs = @(
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", "`"$prefetchScript`"",
"-ProjectRoot", "`"$Global:ProjectRoot`"",
"-ConfigPath", "`"$Global:ConfigPath`"",
"-MaxParallel", "$MaxParallel",
"-LogPath", "`"$prefetchLog`""
)
try {
$proc = Start-Process -FilePath $psExe -ArgumentList $prefetchArgs -PassThru -WindowStyle Hidden
Write-Ok "Application download prefetch started in the background (max $MaxParallel downloads)."
Write-Info "Prefetch log: $prefetchLog"
Write-StructuredLog -Level PREFETCH -Message ("Started process {0}; log={1}" -f $proc.Id, $prefetchLog)
return [pscustomobject]@{ Process = $proc; LogPath = $prefetchLog; Started = Get-Date }
} catch {
Write-Warn "Could not start application download prefetch: $($_.Exception.Message)"
return $null
}
}
function Wait-ApplicationDownloadPrefetch {
param([object]$Prefetch)
if (-not $Prefetch -or -not $Prefetch.Process) { return }
$proc = $Prefetch.Process
Write-Info "Waiting for application prefetch to finish before sequential installs..."
while (-not $proc.HasExited) {
$elapsed = (Get-Date) - $Prefetch.Started
Write-StatusInPlace ("Application downloads still running... elapsed {0:hh\:mm\:ss}" -f $elapsed)
Start-Sleep -Seconds 2
try { $proc.Refresh() } catch { break }
}
Clear-StatusInPlace
try { $proc.Refresh() } catch { }
if ($proc.ExitCode -eq 0) {
Write-Ok "Application download prefetch completed."
} else {
Write-Warn "Application prefetch exited with code $($proc.ExitCode). Sequential install will continue and may download missing installers."
}
Write-StructuredLog -Level PREFETCH -Message ("Finished process {0}; exit={1}; log={2}" -f $proc.Id, $proc.ExitCode, $Prefetch.LogPath)
}
# =============================================================================
# DOWNLOAD / INSTALL HELPERS
# =============================================================================
function Invoke-DownloadFile {
param(
[Parameter(Mandatory)][string]$Url,
[Parameter(Mandatory)][string]$Destination,
[int]$RetryCount = 2,
[int64]$MinimumBytes = 1024,
[string]$ExpectedSha256 = "",
[bool]$RequireValidSignature = $false
)
$dir = Split-Path -Parent $Destination
Ensure-Directory $dir
if (Test-Path $Destination) {
$existing = Get-Item -LiteralPath $Destination -ErrorAction SilentlyContinue
if ($existing -and $existing.Length -ge $MinimumBytes) {
if (-not (Test-FileSha256 -Path $Destination -ExpectedSha256 $ExpectedSha256)) {
Write-Warn ("Cached file failed hash verification; re-downloading: {0}" -f (Split-Path -Leaf $Destination))
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
} elseif ($RequireValidSignature -and $true -ne (Test-DownloadedFileSignature -Path $Destination)) {
Write-Warn ("Cached file failed required signature validation; re-downloading: {0}" -f (Split-Path -Leaf $Destination))
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
} else {
Write-Ok ("Using cached download: {0}" -f (Split-Path -Leaf $Destination))
Write-StructuredLog -Level DOWNLOAD -Message ("Cache hit: {0}; bytes={1}" -f $Destination, $existing.Length)
return $true
}
} else {
Write-Warn ("Cached file is missing or too small; re-downloading: {0}" -f (Split-Path -Leaf $Destination))
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
}
}
for ($i = 0; $i -le $RetryCount; $i++) {
$partial = "$Destination.partial"
try {
Remove-Item -LiteralPath $partial -Force -ErrorAction SilentlyContinue
Write-StructuredLog -Level DOWNLOAD -Message ("URL={0}; Destination={1}" -f $Url, $Destination)
Write-StatusInPlace ("Downloading: {0}" -f (Split-Path -Leaf $Destination))
Invoke-WebRequest -Uri $Url -OutFile $partial -UseBasicParsing -ErrorAction Stop
$downloaded = Get-Item -LiteralPath $partial -ErrorAction Stop
if ($downloaded.Length -lt $MinimumBytes) {
throw "Downloaded file is unexpectedly small ($($downloaded.Length) bytes)."
}
Move-Item -LiteralPath $partial -Destination $Destination -Force
Clear-StatusInPlace
if (-not (Test-FileSha256 -Path $Destination -ExpectedSha256 $ExpectedSha256)) {
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
throw "Downloaded file failed SHA256 verification."
}
$signatureOk = Test-DownloadedFileSignature -Path $Destination
if ($RequireValidSignature -and $true -ne $signatureOk) {
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
throw "Downloaded file failed required Authenticode signature validation."
}
Write-Ok ("Downloaded: {0}" -f (Split-Path -Leaf $Destination))
return $true
} catch {
Clear-StatusInPlace
Remove-Item -LiteralPath $partial -Force -ErrorAction SilentlyContinue
if ($i -ge $RetryCount) {
Write-Fail ("Download failed: {0} ({1})" -f $Url, $_.Exception.Message)
return $false
}
Write-Warn ("Download retry {0} for {1}: {2}" -f ($i + 1), $Url, $_.Exception.Message)
Start-Sleep -Seconds 2
}
}
return $false
}
function Get-InstalledRegistryDisplayName {
param([Parameter(Mandatory)][string]$NameLike)
$roots = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
)
foreach ($r in $roots) {
try {
Get-ChildItem $r -ErrorAction SilentlyContinue | ForEach-Object {
try {
$p = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
if ($p -and $p.DisplayName -like "*$NameLike*") { return $p.DisplayName }
} catch { }
}
} catch { }
}
return $null
}
function Invoke-SilentExeInstall {
param(
[Parameter(Mandatory)][string]$Path,
[string[]]$Arguments = @("/S"),
[int]$TimeoutSeconds = 600
)
Write-Info ("Running silent installer: {0} {1}" -f (Split-Path -Leaf $Path), ($Arguments -join ' '))
Write-StructuredLog -Level COMMAND -Message ("Installer path: {0}" -f $Path)
$proc = Start-Process -FilePath $Path -ArgumentList $Arguments -PassThru -WindowStyle Hidden
if (-not $proc.WaitForExit($TimeoutSeconds * 1000)) {
try { $proc.Kill() } catch { }
throw "Installer did not complete within $TimeoutSeconds seconds: $Path"
}
Write-StructuredLog -Level COMMAND -Message ("Installer exit code: {0}" -f $proc.ExitCode)
return $proc.ExitCode
}
function Invoke-LoggedCommand {
param(
[Parameter(Mandatory)][string]$FilePath,
[string[]]$Arguments = @(),
[string]$DisplayName = ""
)
$label = if ([string]::IsNullOrWhiteSpace($DisplayName)) { (Split-Path -Leaf $FilePath) } else { $DisplayName }
$commandLine = "{0} {1}" -f $FilePath, ($Arguments -join ' ')
Write-StructuredLog -Level COMMAND -Message $commandLine
$output = @()
$exitCode = 1
try {
$output = @(& $FilePath @Arguments 2>&1)
$exitCode = if ($null -ne $LASTEXITCODE) { [int]$LASTEXITCODE } else { 0 }
} catch {
$output = @($_.Exception.Message)
$exitCode = 1
}
foreach ($line in $output) {
$text = [string]$line
if (-not [string]::IsNullOrWhiteSpace($text)) {
Write-StructuredLog -Level OUTPUT -Message ("{0}> {1}" -f $label, $text.TrimEnd())
}
}
Write-StructuredLog -Level COMMAND -Message ("{0} exit code: {1}" -f $label, $exitCode)
return [pscustomobject]@{
ExitCode = $exitCode
Output = $output
}
}
function Invoke-LoggedProcessWithProgress {
param(
[Parameter(Mandatory)][string]$FilePath,
[string[]]$Arguments = @(),
[string]$DisplayName = "",
[string]$StatusMessage = ""
)
$label = if ([string]::IsNullOrWhiteSpace($DisplayName)) { (Split-Path -Leaf $FilePath) } else { $DisplayName }
$status = if ([string]::IsNullOrWhiteSpace($StatusMessage)) { "Running $label" } else { $StatusMessage }
$outFile = [System.IO.Path]::GetTempFileName()
$errFile = [System.IO.Path]::GetTempFileName()
try {
Write-StructuredLog -Level COMMAND -Message ("{0} {1}" -f $FilePath, ($Arguments -join ' '))
$proc = Start-Process -FilePath $FilePath -ArgumentList $Arguments -RedirectStandardOutput $outFile -RedirectStandardError $errFile -WindowStyle Hidden -PassThru
$start = Get-Date
while (-not $proc.HasExited) {
$elapsed = (Get-Date) - $start
Write-StatusInPlace ("{0} [{1:hh\:mm\:ss}]" -f $status, $elapsed)
Start-Sleep -Seconds 2
try { $proc.Refresh() } catch { }
}
Clear-StatusInPlace
$output = @()
foreach ($path in @($outFile, $errFile)) {
if (Test-Path $path) {
$output += Get-Content -LiteralPath $path -ErrorAction SilentlyContinue
}
}
foreach ($line in $output) {
$text = [string]$line
if (-not [string]::IsNullOrWhiteSpace($text)) {
Write-StructuredLog -Level OUTPUT -Message ("{0}> {1}" -f $label, $text.TrimEnd())
}
}
Write-StructuredLog -Level COMMAND -Message ("{0} exit code: {1}" -f $label, $proc.ExitCode)
return [pscustomobject]@{ ExitCode = $proc.ExitCode; Output = $output }
} catch {
Clear-StatusInPlace
Write-StructuredLog -Level ERROR -Message ("{0} failed to start or run: {1}" -f $label, $_.Exception.Message)
throw
} finally {
Clear-StatusInPlace
Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue
}
}
# =============================================================================
# WINGET ENSURE + MSSTORE FIX (item 9)
# =============================================================================
function Ensure-Winget {
if (Test-CommandExists "winget") {
Write-Ok "WinGet is available."
Repair-WingetSources
return $true
}
if (-not $Global:Config.winget.installIfMissing) {
Write-Warn "WinGet is missing and installIfMissing is disabled."
return $false
}
Write-Info "WinGet was not found. Downloading Microsoft App Installer package..."
$bundle = Get-SafeDownloadCacheFilePath -FileName "Microsoft.DesktopAppInstaller.msixbundle"
if (Invoke-DownloadFile -Url "https://aka.ms/getwinget" -Destination $bundle) {
try {
Add-AppxPackage -Path $bundle
Write-Ok "WinGet package installed. A new shell may be required to pick it up."
} catch {
Write-Fail "Could not install WinGet automatically: $($_.Exception.Message)"
return $false
}
}
if (-not (Test-CommandExists "winget")) {
Write-Warn "WinGet still not detected. Install App Installer manually and re-run."
return $false
}
Repair-WingetSources
return $true
}
function Repair-WingetSources {
if (-not $Global:Config.winget.removeMsstoreSource) { return }