-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetup-DevContainers.ps1
More file actions
2286 lines (1913 loc) · 83.5 KB
/
Copy pathSetup-DevContainers.ps1
File metadata and controls
2286 lines (1913 loc) · 83.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
# SPDX-License-Identifier: NCSA
#===============================================================================
# Setup-DevContainers.ps1 - DevContainers environment setup for Windows 11
#
# DESCRIPTION:
# Automated setup of VS Code DevContainers on Windows 11 via WSL2.
# Handles WSL2 enablement, distro installation, and tooling setup.
# Non-interactive mode available for automation.
#
# REQUIREMENTS:
# Windows 11 22H2+
# PowerShell 5.1+ or PowerShell 7+
# Administrator privileges
#
# USAGE:
# .\Setup-DevContainers.ps1
# .\Setup-DevContainers.ps1 -DryRun -Verbose
# .\Setup-DevContainers.ps1 -NonInteractive
#
# OPTIONS:
# -Distro Distro to install: Debian (only supported distro)
# -Resume Resume setup after reboot
# -DryRun Show what would be done without making changes
# -NonInteractive Skip all prompts, use defaults
# -SkipApps Skip Windows Terminal/VS Code installation
# -SkipFonts Skip MesloLGS NF font installation
# -Force Force reinstall of Windows apps even if present
# -Help Show help message
#
# LICENSE: NCSA
#===============================================================================
#Requires -Version 5.1
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
[Parameter(HelpMessage = "Linux distribution to install")]
[ValidateSet('Debian')]
[string]$Distro = 'Debian',
[Parameter(HelpMessage = "Resume setup after reboot")]
[switch]$Resume,
[Parameter(HelpMessage = "Preview without making changes")]
[switch]$DryRun,
[Parameter(HelpMessage = "Skip all prompts, use defaults")]
[switch]$NonInteractive,
[Parameter(HelpMessage = "Skip Windows Terminal/VS Code installation")]
[switch]$SkipApps,
[Parameter(HelpMessage = "Skip MesloLGS NF font installation")]
[switch]$SkipFonts,
[Parameter(HelpMessage = "Overwrite existing configuration")]
[switch]$Force,
[Parameter(HelpMessage = "Show help message")]
[switch]$Help
)
# Satisfy PSScriptAnalyzer - parameters are used in nested function scopes
$null = $Distro, $Resume, $DryRun, $NonInteractive, $SkipApps, $SkipFonts, $Force, $Help
#-------------------------------------------------------------------------------
# Strict Mode
#-------------------------------------------------------------------------------
Set-StrictMode -Version 3.0 # Explicit version for deterministic behavior
$ErrorActionPreference = 'Stop'
$script:OriginalProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
$script:SCRIPT_NAME = $MyInvocation.MyCommand.Name
$script:SCRIPT_VERSION = "1.1.0"
$script:LOG_DIR = "$env:LOCALAPPDATA\DevContainersSetup"
$script:LOG_FILE = "$script:LOG_DIR\setup.log"
$script:STATE_REG_PATH = "HKCU:\Software\DevContainersSetup"
$script:RESUME_TASK_NAME = "DevContainersSetup_Resume"
# Mutex for preventing concurrent execution
$script:SETUP_MUTEX_NAME = "Global\DevContainersSetup_Mutex"
$script:SetupMutex = $null
# Exit codes
$script:EXIT_SUCCESS = 0
$script:EXIT_GENERAL_ERROR = 1
$script:EXIT_NOT_ADMIN = 2
$script:EXIT_WSL_FAILED = 4
$script:EXIT_DISTRO_FAILED = 5
$script:EXIT_WINGET_FAILED = 6
$script:EXIT_REBOOT_REQUIRED = 7
$script:EXIT_NO_SLOT_AVAILABLE = 9
# Supported distros
$script:SUPPORTED_DISTROS = @{
'Debian' = @{
DisplayName = 'Debian 13 Trixie'
}
}
# VS Code extensions required for DevContainers
$script:VSCODE_EXTENSIONS = @(
'ms-vscode-remote.remote-containers'
'ms-vscode-remote.remote-wsl'
)
# MesloLGS NF font files (bundled with repo for Powerlevel10k)
$script:MESLO_FONT_FILES = @(
'MesloLGS NF Regular.ttf'
'MesloLGS NF Bold.ttf'
'MesloLGS NF Italic.ttf'
'MesloLGS NF Bold Italic.ttf'
)
$script:MESLO_FONT_NAME = "MesloLGS NF"
#-------------------------------------------------------------------------------
# Logging Functions
#-------------------------------------------------------------------------------
function Initialize-Logging {
if (-not (Test-Path $script:LOG_DIR)) {
New-Item -ItemType Directory -Path $script:LOG_DIR -Force | Out-Null
}
# Clear or create log file
"" | Out-File -FilePath $script:LOG_FILE -Encoding UTF8
}
function Write-SetupLog {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive CLI requires colored console output')]
param(
[Parameter(Mandatory)]
[string]$Level,
[Parameter(Mandatory)]
[string]$Message,
[Parameter(Mandatory)]
[string]$Color
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logLine = "[$Level] $timestamp - $Message"
# Write to log file
Add-Content -Path $script:LOG_FILE -Value $logLine -Encoding UTF8
# Write to console with color
Write-Host $logLine -ForegroundColor $Color
}
function Write-LogInfo {
param([string]$Message)
Write-SetupLog -Level "INFO " -Message $Message -Color "Cyan"
}
function Write-LogSuccess {
param([string]$Message)
Write-SetupLog -Level "OK " -Message $Message -Color "Green"
}
function Write-LogWarn {
param([string]$Message)
Write-SetupLog -Level "WARN " -Message $Message -Color "Yellow"
}
function Write-LogError {
param([string]$Message)
Write-SetupLog -Level "ERROR" -Message $Message -Color "Red"
}
function Write-LogDebug {
param([string]$Message)
if ($VerbosePreference -eq 'Continue' -or $PSBoundParameters['Verbose']) {
Write-SetupLog -Level "DEBUG" -Message $Message -Color "DarkGray"
}
}
function Write-LogStep {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive CLI requires colored console output')]
param(
[Parameter(Mandatory)]
[string]$Step,
[Parameter(Mandatory)]
[string]$Description
)
Write-Host ""
Write-Host "[Step $Step] " -ForegroundColor Blue -NoNewline
Write-Host $Description -ForegroundColor White
Write-Host ("-" * 60) -ForegroundColor DarkGray
Add-Content -Path $script:LOG_FILE -Value "" -Encoding UTF8
Add-Content -Path $script:LOG_FILE -Value "[Step $Step] $Description" -Encoding UTF8
Add-Content -Path $script:LOG_FILE -Value ("-" * 60) -Encoding UTF8
}
#-------------------------------------------------------------------------------
# Utility Functions
#-------------------------------------------------------------------------------
function Test-Administrator {
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Exit-WithError {
param(
[string]$Message,
[int]$ExitCode = $script:EXIT_GENERAL_ERROR
)
Write-LogError $Message
Write-LogInfo "Log file: $script:LOG_FILE"
exit $ExitCode
}
function Invoke-WithDryRun {
param(
[Parameter(Mandatory)]
[scriptblock]$ScriptBlock,
[string]$Description
)
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would execute: $Description"
return $null
}
Write-LogDebug "Executing: $Description"
return & $ScriptBlock
}
function Get-Confirmation {
param(
[Parameter(Mandatory)]
[string]$Prompt,
[bool]$Default = $true
)
if ($NonInteractive) {
Write-LogDebug "Non-interactive mode: using default ($Default)"
return $Default
}
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would prompt: $Prompt"
return $true
}
$defaultText = if ($Default) { "[Y/n]" } else { "[y/N]" }
$response = Read-Host "$Prompt $defaultText"
if ([string]::IsNullOrWhiteSpace($response)) {
return $Default
}
return $response -match '^[Yy]'
}
function Get-PosixEscapedPath {
<#
.SYNOPSIS
Escapes a path for use in POSIX single-quoted strings.
.DESCRIPTION
Replaces single quotes with the POSIX-safe sequence: '\''
This closes the quote, adds an escaped quote, reopens the quote.
Required when Windows usernames contain apostrophes (e.g., O'Connor).
#>
param([Parameter(Mandatory)][string]$Path)
return $Path -replace "'", "'\\''"
}
function Get-SystemArchitecture {
<#
.SYNOPSIS
Detects the system CPU architecture.
.DESCRIPTION
Uses .NET RuntimeInformation for reliable architecture detection across
PowerShell versions. Falls back to environment variables if needed.
.OUTPUTS
Returns 'x64' or 'ARM64' based on system architecture.
#>
try {
$arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
switch ($arch) {
'X64' { return 'x64' }
'Arm64' { return 'ARM64' }
default {
Write-LogDebug "Unknown architecture from RuntimeInformation: $arch"
}
}
}
catch {
Write-LogDebug "RuntimeInformation not available: $_"
}
# Fallback to environment variable for older PowerShell or edge cases
switch ($env:PROCESSOR_ARCHITECTURE) {
'AMD64' { return 'x64' }
'ARM64' { return 'ARM64' }
default {
Write-LogWarn "Could not detect architecture, defaulting to x64"
return 'x64'
}
}
}
#-------------------------------------------------------------------------------
# Script Locking
#-------------------------------------------------------------------------------
function Enter-ScriptLock {
<#
.SYNOPSIS
Acquires an exclusive lock to prevent concurrent script execution.
.OUTPUTS
Returns $true if lock acquired, $false if another instance is running.
#>
try {
$createdNew = $false
$script:SetupMutex = New-Object System.Threading.Mutex($true, $script:SETUP_MUTEX_NAME, [ref]$createdNew)
if (-not $createdNew) {
# Mutex exists, try to acquire it with timeout
$acquired = $script:SetupMutex.WaitOne(0) # Non-blocking
if (-not $acquired) {
Write-LogError "Another instance of DevContainers Setup is already running"
return $false
}
}
Write-LogDebug "Acquired exclusive script lock"
return $true
}
catch [System.Threading.AbandonedMutexException] {
# Previous instance crashed without releasing - we now own it
Write-LogDebug "Acquired abandoned script lock (previous instance crashed)"
return $true
}
catch {
Write-LogWarn "Could not acquire script lock: $_"
# Allow script to run anyway - lock is a safety feature, not critical
return $true
}
}
function Exit-ScriptLock {
<#
.SYNOPSIS
Releases the exclusive lock when script completes.
#>
if ($script:SetupMutex) {
try {
$script:SetupMutex.ReleaseMutex()
$script:SetupMutex.Dispose()
Write-LogDebug "Released script lock"
}
catch {
# Intentionally suppressed: cleanup errors during mutex release are non-critical
$null = $_
}
$script:SetupMutex = $null
}
}
#-------------------------------------------------------------------------------
# Virtualization Check
#-------------------------------------------------------------------------------
function Test-VirtualizationEnabled {
<#
.SYNOPSIS
Checks if hardware virtualization is enabled and available.
.DESCRIPTION
Uses multiple detection methods because:
- When hypervisor is already running (WSL2, Hyper-V), VirtualizationFirmwareEnabled
returns false even though virtualization IS working
- HypervisorPresent = true means virtualization is already active
.OUTPUTS
Returns hashtable with Enabled (bool) and Message (string).
#>
try {
# Method 1: Check if hypervisor is already present (most reliable when WSL2/Hyper-V active)
$computerSystem = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue
if ($computerSystem.HypervisorPresent -eq $true) {
return @{ Enabled = $true; Message = "Hypervisor already active" }
}
# Method 2: Check firmware setting (only reliable when hypervisor is NOT running)
$cpu = Get-CimInstance -ClassName Win32_Processor -ErrorAction SilentlyContinue
if ($cpu.VirtualizationFirmwareEnabled -eq $true) {
return @{ Enabled = $true; Message = "Virtualization enabled in firmware" }
}
# Method 3: Check via Get-ComputerInfo (Windows 10+)
try {
$compInfo = Get-ComputerInfo -Property HyperV* -ErrorAction SilentlyContinue
if ($compInfo.HyperVisorPresent -eq $true) {
return @{ Enabled = $true; Message = "Hypervisor present (Get-ComputerInfo)" }
}
if ($compInfo.HyperVRequirementVirtualizationFirmwareEnabled -eq $true) {
return @{ Enabled = $true; Message = "Virtualization enabled (Get-ComputerInfo)" }
}
}
catch {
# Intentionally suppressed: Get-ComputerInfo may not be available on all systems
$null = $_
}
# If we reach here without confirming enabled, check if it's explicitly disabled
if ($cpu.VirtualizationFirmwareEnabled -eq $false -and $computerSystem.HypervisorPresent -eq $false) {
return @{
Enabled = $false
Message = "Hardware virtualization is disabled in BIOS/UEFI. Enable VT-x/AMD-V."
}
}
# Can't determine - assume enabled and let WSL fail with its own error if not
return @{ Enabled = $true; Message = "Virtualization status unclear (assuming enabled)" }
}
catch {
# Can't verify - assume enabled and let WSL fail with its own error if not
return @{ Enabled = $true; Message = "Could not verify virtualization (assuming enabled)" }
}
}
#-------------------------------------------------------------------------------
# WSL Command Helpers
#-------------------------------------------------------------------------------
function Test-WslFileTransferIntegrity {
<#
.SYNOPSIS
Verifies a file was transferred to WSL without truncation by comparing sizes.
.DESCRIPTION
Accounts for CR characters (0x0D) that are stripped during transfer via tr -d '\r'.
This ensures the integrity check works correctly for both LF and CRLF source files.
.PARAMETER SourcePath
The Windows source file path.
.PARAMETER WslPath
The destination path inside WSL.
.PARAMETER Distro
The WSL distribution name.
.OUTPUTS
Returns $true if sizes match. Throws on mismatch or error.
#>
param(
[Parameter(Mandatory)]
[string]$SourcePath,
[Parameter(Mandatory)]
[string]$WslPath,
[Parameter(Mandatory)]
[string]$Distro
)
$fileName = Split-Path -Leaf $SourcePath
# Read source file as bytes to accurately count CR characters
$sourceBytes = [System.IO.File]::ReadAllBytes($SourcePath)
# Count CR bytes (0x0D) that tr -d '\r' will strip during transfer
$crCount = 0
foreach ($byte in $sourceBytes) {
if ($byte -eq 0x0D) { $crCount++ }
}
# Expected size is original minus stripped CRs
$expectedSize = $sourceBytes.Length - $crCount
$sizeOutput = wsl -d $Distro -u root --cd /tmp -- stat -c '%s' $WslPath 2>&1
$transferredSize = ($sizeOutput | Out-String).Trim() -replace '\x00', '' -replace '\r', ''
if ($LASTEXITCODE -ne 0 -or -not $transferredSize) {
throw "Could not verify file transfer: stat failed for $WslPath (exit code: $LASTEXITCODE)"
}
if ([long]$transferredSize -ne $expectedSize) {
throw "File integrity check failed: $fileName size mismatch (expected: $expectedSize bytes, got: $transferredSize bytes)"
}
if ($crCount -gt 0) {
Write-LogDebug "Verified transfer: $fileName ($expectedSize bytes, stripped $crCount CR chars)"
} else {
Write-LogDebug "Verified transfer: $fileName ($expectedSize bytes)"
}
return $true
}
#-------------------------------------------------------------------------------
# Debian Rootfs Download
#-------------------------------------------------------------------------------
function Get-DebianRootfs {
<#
.SYNOPSIS
Downloads Debian 13 Trixie rootfs from official WSL distribution.
.DESCRIPTION
Downloads the architecture-specific .wsl file from salsa.debian.org,
verifies the SHA256 checksum, and returns the path to the tarball.
The .wsl format is a direct tarball ready for wsl --import.
.OUTPUTS
Returns the path to the downloaded .wsl tarball file.
.LINK
https://github.com/microsoft/WSL/blob/master/distributions/DistributionInfo.json
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '',
Justification = 'Rootfs is singular - abbreviation for root filesystem')]
param(
[Parameter(Mandatory)]
[string]$OutputPath
)
# Architecture-specific URLs and checksums from Microsoft WSL distribution catalog
$debianUrls = @{
'x64' = @{
Url = 'https://salsa.debian.org/debian/WSL/-/jobs/7949331/artifacts/raw/Debian_WSL_AMD64_v1.22.0.0.wsl'
SHA256 = '543123ccc5f838e63dac81634fb0223dc8dcaa78fdb981387d625feb1ed168c7'
}
'ARM64' = @{
Url = 'https://salsa.debian.org/debian/WSL/-/jobs/7949331/artifacts/raw/Debian_WSL_ARM64_v1.22.0.0.wsl'
SHA256 = '5701f1add55f8cf3b56528109a6220ae5c89f2189d7ae97b9a4b5302b80e967c'
}
}
$systemArch = Get-SystemArchitecture
Write-LogDebug "System architecture: $systemArch"
if (-not $debianUrls.ContainsKey($systemArch)) {
throw "Unsupported architecture: $systemArch. Supported: x64, ARM64"
}
$archInfo = $debianUrls[$systemArch]
$downloadUrl = $archInfo.Url
$expectedHash = $archInfo.SHA256
Write-LogInfo "Downloading Debian 13 Trixie ($systemArch)..."
Write-LogDebug "URL: $downloadUrl"
try {
$downloadStart = Get-Date
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $downloadUrl -OutFile $OutputPath -UseBasicParsing -ErrorAction Stop
$downloadTime = (Get-Date) - $downloadStart
$fileSize = (Get-Item $OutputPath).Length
Write-LogDebug "Downloaded $([Math]::Round($fileSize / 1MB, 1)) MB in $([Math]::Round($downloadTime.TotalSeconds, 1))s"
# Verify SHA256 checksum
Write-LogInfo "Verifying SHA256 checksum..."
$actualHash = (Get-FileHash -Path $OutputPath -Algorithm SHA256).Hash.ToLower()
if ($actualHash -ne $expectedHash.ToLower()) {
throw "SHA256 checksum mismatch!`nExpected: $expectedHash`nActual: $actualHash"
}
Write-LogSuccess "Checksum verified"
# Verify file size is reasonable (minimal rootfs can be as small as ~10MB)
if ($fileSize -lt 10MB) {
throw "Rootfs file suspiciously small ($([Math]::Round($fileSize / 1MB, 1)) MB)"
}
Write-LogSuccess "Debian 13 Trixie rootfs ready ($([Math]::Round($fileSize / 1MB, 0)) MB)"
return $OutputPath
}
catch {
if (Test-Path $OutputPath) {
Remove-Item $OutputPath -Force -ErrorAction SilentlyContinue
}
throw
}
}
#-------------------------------------------------------------------------------
# State Management (for reboot resume)
#-------------------------------------------------------------------------------
function Save-SetupState {
param(
[int]$Phase,
[string]$SelectedDistro
)
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would save state: Phase=$Phase, Distro=$SelectedDistro"
return
}
if (-not (Test-Path $script:STATE_REG_PATH)) {
New-Item -Path $script:STATE_REG_PATH -Force | Out-Null
}
Set-ItemProperty -Path $script:STATE_REG_PATH -Name "Phase" -Value $Phase
Set-ItemProperty -Path $script:STATE_REG_PATH -Name "Distro" -Value $SelectedDistro
Set-ItemProperty -Path $script:STATE_REG_PATH -Name "Timestamp" -Value (Get-Date -Format "o")
Set-ItemProperty -Path $script:STATE_REG_PATH -Name "ScriptPath" -Value $PSCommandPath
Write-LogDebug "Saved state: Phase=$Phase, Distro=$SelectedDistro"
}
function Get-SetupState {
if (-not (Test-Path $script:STATE_REG_PATH)) {
return $null
}
try {
$regProps = Get-ItemProperty -Path $script:STATE_REG_PATH -ErrorAction SilentlyContinue
if (-not $regProps) { return $null }
# Safe property access compatible with Strict Mode 3.0
$phase = if ($regProps.PSObject.Properties['Phase']) { $regProps.Phase } else { $null }
$distro = if ($regProps.PSObject.Properties['Distro']) { $regProps.Distro } else { $null }
if ($phase -and $distro) {
return @{
Phase = $phase
Distro = $distro
Timestamp = if ($regProps.PSObject.Properties['Timestamp']) { $regProps.Timestamp } else { $null }
ScriptPath = if ($regProps.PSObject.Properties['ScriptPath']) { $regProps.ScriptPath } else { $null }
}
}
}
catch {
Write-LogDebug "Error reading state: $_"
}
return $null
}
function Clear-SetupState {
# Clean up scheduled task if it exists (ignore errors if task doesn't exist)
try {
$null = schtasks.exe /delete /tn $script:RESUME_TASK_NAME /f 2>&1
Write-LogDebug "Cleaned up resume task (if existed)"
}
catch {
# Task didn't exist - that's fine
Write-LogDebug "No resume task to clean up"
}
# Clean up registry state
if (Test-Path $script:STATE_REG_PATH) {
Remove-Item -Path $script:STATE_REG_PATH -Recurse -Force -ErrorAction SilentlyContinue
Write-LogDebug "Cleared saved registry state"
}
# Note: Mutex lock is released in Exit-ScriptLock called from finally block
}
function Request-Reboot {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive CLI requires colored console output')]
param(
[int]$NextPhase,
[string]$SelectedDistro
)
Save-SetupState -Phase $NextPhase -SelectedDistro $SelectedDistro
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would request reboot and schedule resume task"
return
}
$scriptPath = $PSCommandPath
$resumeCmd = "powershell.exe -ExecutionPolicy Bypass -NoProfile -WindowStyle Normal -File `"$scriptPath`" -Resume"
# Method 1: Task Scheduler (works for all users, most reliable)
Write-LogDebug "Creating scheduled task for resume..."
# Delete existing task if present
$null = schtasks.exe /delete /tn $script:RESUME_TASK_NAME /f 2>&1
# Create task to run at next logon with highest privileges
# Using /rl HIGHEST ensures admin elevation
$taskResult = schtasks.exe /create /tn $script:RESUME_TASK_NAME /tr $resumeCmd /sc ONLOGON /rl HIGHEST /f 2>&1
$taskExitCode = $LASTEXITCODE
if ($taskExitCode -eq 0) {
Write-LogDebug "Created scheduled task: $script:RESUME_TASK_NAME"
}
else {
Write-LogWarn "Task Scheduler method failed (exit code: $taskExitCode)"
Write-LogDebug "Task Scheduler output: $taskResult"
# Method 2: RunOnce fallback (only works for admin accounts)
Write-LogInfo "Attempting RunOnce registry fallback..."
try {
# Use exclamation prefix to defer deletion until after execution
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce" `
-Name "!DevContainersSetup" -Value $resumeCmd -ErrorAction Stop
Write-LogDebug "Created RunOnce registry entry"
Write-LogWarn "Note: RunOnce only works if logged in as Administrator account"
}
catch {
Write-LogError "Could not create resume mechanism: $_"
Write-LogWarn "Please run this script again with -Resume flag after reboot"
}
}
Write-Host ""
Write-LogWarn "==============================================================="
Write-LogWarn " SYSTEM RESTART REQUIRED"
Write-LogWarn "==============================================================="
Write-Host ""
Write-LogInfo "WSL2 features have been enabled and require a restart."
Write-LogInfo "Setup will resume automatically after restart."
Write-Host ""
if (-not $NonInteractive) {
$restart = Get-Confirmation -Prompt "Restart now?" -Default $true
if ($restart) {
Write-LogInfo "Restarting computer in 5 seconds..."
Start-Sleep -Seconds 5
Restart-Computer -Force
}
}
Write-Host ""
Write-LogInfo "Please restart your computer manually, then setup will continue."
Write-LogInfo "Or run: shutdown /r /t 0"
exit $script:EXIT_REBOOT_REQUIRED
}
#-------------------------------------------------------------------------------
# Configuration Functions
#-------------------------------------------------------------------------------
function Initialize-WslConfig {
Write-LogInfo "Configuring WSL settings (.wslconfig)..."
$wslConfigPath = Join-Path $env:USERPROFILE ".wslconfig"
$configChanged = $false
# Calculate 80% of system RAM for WSL2 memory limit
$totalRamBytes = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory
$wslMemoryGB = [Math]::Floor(($totalRamBytes * 0.8) / 1GB)
# Ensure minimum of 4GB
$wslMemoryGB = [Math]::Max($wslMemoryGB, 4)
$memoryConfig = "${wslMemoryGB}GB"
Write-LogDebug "System RAM: $([Math]::Round($totalRamBytes / 1GB, 1))GB, WSL2 limit: $memoryConfig (80%)"
# Read existing config
$configContent = ""
if (Test-Path $wslConfigPath) {
$configContent = Get-Content $wslConfigPath -Raw -ErrorAction SilentlyContinue
if (-not $configContent) { $configContent = "" }
}
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would configure .wslconfig with memory=$memoryConfig and autoMemoryReclaim=gradual"
return
}
# Helper function to extract section content (for scoped matching)
# Matches from [section] until next [section] or end of file
$getSectionContent = {
param([string]$Content, [string]$SectionName)
$pattern = "\[$SectionName\][\s\S]*?(?=\n\[|\z)"
$match = [regex]::Match($Content, $pattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($match.Success) { return $match.Value } else { return "" }
}
# Extract section contents for scoped matching
$wsl2Section = & $getSectionContent $configContent "wsl2"
$experimentalSection = & $getSectionContent $configContent "experimental"
# Ensure [wsl2] section exists with recommended settings
if ($configContent -notmatch "\[wsl2\]") {
$configContent = "[wsl2]`nmemory=$memoryConfig`nlocalhostForwarding=true`n`n" + $configContent
$configChanged = $true
Write-LogDebug "Added [wsl2] section with memory=$memoryConfig"
}
elseif ($wsl2Section -notmatch "(?m)^memory\s*=") {
# Add memory setting under existing [wsl2] section (only if not in that section)
$configContent = $configContent -replace "(\[wsl2\])", "`$1`nmemory=$memoryConfig"
$configChanged = $true
Write-LogDebug "Added memory=$memoryConfig to existing [wsl2] section"
}
# Re-extract experimental section after potential changes
$experimentalSection = & $getSectionContent $configContent "experimental"
# DISABLE sparse VHD due to current WSL2 bugs
if ($configContent -notmatch "\[experimental\]") {
$configContent += "`n[experimental]`nsparseVhd=false`nautoMemoryReclaim=gradual`n"
$configChanged = $true
Write-LogDebug "Added [experimental] section with sparseVhd=false"
}
elseif ($experimentalSection -match "(?m)^sparseVhd\s*=\s*true") {
$configContent = $configContent -replace "sparseVhd\s*=\s*true", "sparseVhd=false"
$configChanged = $true
Write-LogDebug "Changed sparseVhd from true to false"
}
elseif ($experimentalSection -notmatch "(?m)^sparseVhd\s*=") {
$configContent = $configContent -replace "(\[experimental\])", "`$1`nsparseVhd=false"
$configChanged = $true
Write-LogDebug "Added sparseVhd=false to existing [experimental] section"
}
# Re-extract experimental section after potential changes
$experimentalSection = & $getSectionContent $configContent "experimental"
# Ensure autoMemoryReclaim is configured (separate from sparseVhd logic)
if ($configContent -match "\[experimental\]" -and $experimentalSection -notmatch "(?m)^autoMemoryReclaim\s*=") {
$configContent = $configContent -replace "(\[experimental\])", "`$1`nautoMemoryReclaim=gradual"
$configChanged = $true
Write-LogDebug "Added autoMemoryReclaim=gradual to existing [experimental] section"
}
if ($configChanged) {
Write-LogInfo "Updating .wslconfig with recommended settings..."
# Backup existing config
if (Test-Path $wslConfigPath) {
$backupPath = "$wslConfigPath.backup"
Copy-Item $wslConfigPath $backupPath -Force
Write-LogDebug "Backed up existing .wslconfig to $backupPath"
}
Set-Content -Path $wslConfigPath -Value $configContent.Trim() -Encoding UTF8
Write-LogSuccess "WSL configuration updated (memory=$memoryConfig, autoMemoryReclaim=gradual)"
# Restart WSL to apply
Write-LogInfo "Restarting WSL to apply configuration..."
wsl --shutdown 2>$null
Start-Sleep -Seconds 3
Write-LogSuccess "WSL restarted with new configuration"
}
else {
Write-LogSuccess "WSL configuration already optimized"
}
# Disable sparse VHD on existing distros to ensure consistency
Disable-SparseOnExistingDistro
}
function Disable-SparseOnExistingDistro {
Write-LogInfo "Checking sparse VHD status on existing distributions..."
# Get list of existing distros
$rawOutput = wsl --list --quiet 2>&1
$distroList = ($rawOutput | Out-String) -replace '\x00', '' -replace '\r', ''
# Handle WSL command failure (e.g., WSL not ready)
if ($LASTEXITCODE -ne 0) {
Write-LogWarn "Could not enumerate WSL distributions (exit code: $LASTEXITCODE)"
Write-LogDebug "WSL output: $distroList"
return
}
$distros = @($distroList -split "`n" | Where-Object { $_ -match '\S' } | ForEach-Object { $_.Trim() })
if ($distros.Count -eq 0) {
Write-LogInfo "No existing distributions to configure"
return
}
Write-LogInfo "Found $($distros.Count) distribution(s) to configure: $($distros -join ', ')"
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would disable sparse VHD for all distributions"
return
}
# Shut down WSL first
Write-LogInfo "Shutting down WSL to configure VHD settings..."
wsl --shutdown 2>$null
Start-Sleep -Seconds 3
$anyChanged = $false
foreach ($distro in $distros) {
if (-not $distro) { continue }
Write-LogInfo "Disabling sparse VHD for: $distro"
# Disable sparse
$result = wsl --manage $distro --set-sparse false 2>&1
$resultStr = ($result | Out-String) -replace '\x00', '' -replace '\r', ''
if ($LASTEXITCODE -eq 0) {
Write-LogSuccess "Disabled sparse VHD for: $distro"
$anyChanged = $true
}
else {
Write-LogDebug "Could not change sparse for ${distro}: $($resultStr.Trim())"
}
}
if ($anyChanged) {
Write-LogSuccess "VHD configuration complete"
}
# WSL restart
Write-LogInfo "Restarting WSL to apply all configuration changes..."
wsl --shutdown 2>$null
Start-Sleep -Seconds 3
Write-LogSuccess "WSL ready for new installations"
}
#-------------------------------------------------------------------------------
# WSL2 Functions
#-------------------------------------------------------------------------------
function Test-WSL2Enabled {
Write-LogDebug "Checking WSL2 feature status..."
try {
$wslFeature = Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -ErrorAction Stop
$vmFeature = Get-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -ErrorAction Stop
$wslEnabled = $wslFeature.State -eq 'Enabled'
$vmEnabled = $vmFeature.State -eq 'Enabled'
Write-LogDebug "WSL feature: $($wslFeature.State), VM Platform: $($vmFeature.State)"
return @{
WSLEnabled = $wslEnabled
VMEnabled = $vmEnabled
AllEnabled = ($wslEnabled -and $vmEnabled)
}
}
catch {
Write-LogDebug "Error checking features: $_"
return @{
WSLEnabled = $false
VMEnabled = $false
AllEnabled = $false
}
}
}
function Initialize-Wsl2DefaultVersion {
<#
.SYNOPSIS
Initializes WSL2 as the default version with automatic kernel update on failure.
.DESCRIPTION
Attempts to set WSL2 as default. If it fails (often due to missing kernel),
automatically runs wsl --update and retries. Provides clear remediation steps
if all attempts fail.
.OUTPUTS
Returns $true if WSL2 is configured successfully, $false on failure.
#>
if ($DryRun) {
Write-LogInfo "[DRY-RUN] Would set WSL2 as default version"
return $true
}
Write-LogDebug "Setting WSL2 as default version..."
$null = wsl --set-default-version 2 2>&1
if ($LASTEXITCODE -eq 0) {
Write-LogDebug "WSL2 set as default successfully"
return $true
}
$firstExitCode = $LASTEXITCODE
Write-LogWarn "Failed to set WSL2 as default (exit code: $firstExitCode)"
Write-LogInfo "Attempting to update WSL kernel..."
# Try wsl --update to install/update kernel component
$updateOutput = wsl --update 2>&1 | Out-String
Write-LogDebug "WSL update output: $($updateOutput.Trim())"
Start-Sleep -Seconds 2
# Retry setting WSL2 as default
Write-LogInfo "Retrying WSL2 default configuration..."
$null = wsl --set-default-version 2 2>&1
if ($LASTEXITCODE -eq 0) {
Write-LogSuccess "WSL2 configured after kernel update"
return $true
}
# Final failure - provide remediation steps
Write-LogError "Failed to configure WSL2 as default after kernel update"
Write-LogError "Exit code: $LASTEXITCODE"
Write-LogError ""
Write-LogError "Manual remediation steps:"
Write-LogError " 1. Run: wsl --update"
Write-LogError " 2. Run: wsl --set-default-version 2"
Write-LogError " 3. If still failing, download kernel: https://aka.ms/wsl2kernel"
Write-LogError " 4. Re-run this script after completing above steps"
return $false
}
function Enable-WSL2Feature {
Write-LogStep "1/7" "Enabling WSL2 features"
$status = Test-WSL2Enabled
$needsReboot = $false
if ($status.AllEnabled) {
Write-LogSuccess "WSL2 features already enabled"
# Ensure WSL2 is set as default version
if (-not (Initialize-Wsl2DefaultVersion)) {
Exit-WithError "Could not configure WSL2 as default version" $script:EXIT_WSL_FAILED
}
return $false # No reboot needed
}