<# DIY build machine, Windows (51.40-T23): make this Windows computer a build machine for DIY's lanes, through WSL2. In PowerShell run as Administrator (Windows PowerShell 5.1 or PowerShell 7), from the folder that holds this file and setup-linux.sh: powershell -ExecutionPolicy Bypass -File setup-windows.ps1 set it up (one restart when WSL is new; it carries on by itself after it) powershell -ExecutionPolicy Bypass -File setup-windows.ps1 -Join join it to your DIY: on your DIY's computer run diy worker add first, then type the code it shows here (or -Join -Code ABCD-EFGH-JKMN) powershell -ExecutionPolicy Bypass -File setup-windows.ps1 -Check say what is there and what is missing, with the step to fix each powershell -ExecutionPolicy Bypass -File setup-windows.ps1 -Remove undo what this script did (the WSL distribution it made, its settings) -Native also install the Windows toolchain for DIY's Windows tests: the MSVC build tools, Rust for MSVC, Node.js, pnpm and Git -Distro the WSL distribution (default Ubuntu-24.04); -SshPort where its sshd listens (default 2222: Windows may hold 22) -DryRun say what would run; -Yes no question before -Remove What it does, in order: 1. Windows 11 22H2 or newer (mirrored networking, which lets your DIY reach the build machine at this computer's own address) 2. WSL2 (wsl --install --no-distribution); when Windows needs the restart, a task carries on at your next sign-in 3. %USERPROFILE%\.wslconfig: networkingMode=mirrored, vmIdleTimeout=-1, and three quarters of the memory for WSL (your other settings stay) 4. the distribution, with systemd on (/etc/wsl.conf), and setup-linux.sh inside it as root, with --ssh-port 5. a Hyper-V firewall rule for the sshd port, inbound to WSL only, from the tailnet when Tailscale is here; the pairing port (7491) is opened the same way only while -Join waits, and closed after The files that run elevated are kept in %ProgramData%\diy-worker, which only Administrators and SYSTEM may change. 6. a task at your sign-in that keeps the distribution running, so the build machine is there while you are signed in to Windows Nothing personal and no secret is in this file or put on the machine by it. The one key that lands here is the public key of your DIY, by -Join, for the diy-worker user inside WSL only, after you typed the code your DIY showed you. Exit: 0 done (or, with -Check, everything is there); 1 something failed or is missing; 2 a usage mistake; 3 a restart is needed first. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'the parameters are read by the functions below, through the script scope')] [CmdletBinding()] param( [switch]$Check, [switch]$Remove, [switch]$Native, [switch]$Join, [string]$Code = '', [string]$Distro = 'Ubuntu-24.04', [int]$SshPort = 2222, [switch]$Resume, [switch]$Yes, [switch]$DryRun ) $ErrorActionPreference = 'Stop' $InformationPreference = 'Continue' $SetupVersion = 1 # The same pins as setup-linux.sh (tools/worker/test/setup-windows.Tests.ps1 checks that they agree). $RustVersion = '1.97.1' $NodeVersion = '24.12.0' $PnpmVersion = '10.28.1' $PairPort = 7491 $WslVmCreator = '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' $TaskResume = 'DIY build machine setup (continue)' $TaskKeep = 'DIY build machine (WSL)' $script:ResumeTaskSet = $false $Site = if ($env:DIY_SITE) { $env:DIY_SITE.TrimEnd('/') } else { 'https://install.vibedout.app' } # ---- the outside world, one function each (the tests replace these) ------------------------------------------------------------- function Get-DataDir { if ($env:DIY_WORKER_PS_ROOT) { return $env:DIY_WORKER_PS_ROOT } return (Join-Path $env:ProgramData 'diy-worker') } function Get-WslConfigPath { return (Join-Path $env:USERPROFILE '.wslconfig') } function Get-WinBuild { return [int](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').CurrentBuildNumber } function Test-Admin { $id = [Security.Principal.WindowsIdentity]::GetCurrent() return ([Security.Principal.WindowsPrincipal]$id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } function Get-TotalMemoryGB { return [int][math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB) } # wsl.exe writes UTF-16 for its own messages; WSL_UTF8=1 makes it UTF-8, so the text can be read. function Invoke-Wsl { param([string[]]$WslArgs) $env:WSL_UTF8 = '1'; $out = & wsl.exe @WslArgs 2>&1 | Out-String; return [pscustomobject]@{ Code = $LASTEXITCODE; Out = $out } } function Invoke-WslLive { param([string[]]$WslArgs) & wsl.exe @WslArgs; return $LASTEXITCODE } function Invoke-Winget { param([string[]]$WingetArgs) $out = & winget.exe @WingetArgs 2>&1 | Out-String; return [pscustomobject]@{ Code = $LASTEXITCODE; Out = $out } } function Test-Command { param([string]$Name) return [bool](Get-Command $Name -ErrorAction SilentlyContinue) } function Get-FwRule { param([string]$Name) return (Get-NetFirewallHyperVRule -Name $Name -ErrorAction SilentlyContinue) } function Add-FwRule { param([string]$Name, [int]$Port, [string]$Remote = 'Any') New-NetFirewallHyperVRule -Name $Name -DisplayName $Name -Direction Inbound -VMCreatorId $WslVmCreator -Protocol TCP -LocalPorts $Port -RemoteAddresses $Remote -Action Allow | Out-Null } # The data folder holds what runs elevated (this script, setup-linux.sh as root in WSL): only Administrators and SYSTEM may change it, so a # program running as an ordinary user cannot change it before the next elevated run (51.40 review 1). Users may read it (read and execute, # nothing more), so -Check run without elevation can still read setup-linux.sh for its Linux list (51.40 review 2, N1). $DataDirGrants = @('*S-1-5-32-544:(OI)(CI)F', '*S-1-5-18:(OI)(CI)F', '*S-1-5-32-545:(OI)(CI)RX') function Protect-DataDir { param([string]$Path) & icacls.exe $Path /setowner '*S-1-5-32-544' /T /C | Out-Null & icacls.exe $Path /inheritance:r /grant:r @DataDirGrants /T /C | Out-Null if ($LASTEXITCODE -ne 0) { throw [System.Exception]::new("setup-windows.ps1: could not limit $Path to Administrators and SYSTEM (icacls)") } } # where the build machine is reached from: the tailnet when Tailscale is here, else any address function Get-RemoteRange { if (Test-Command 'tailscale.exe') { return '100.64.0.0/10' } return 'Any' } function Unregister-FwRule { param([string]$Name) Remove-NetFirewallHyperVRule -Name $Name -ErrorAction SilentlyContinue } function Get-Task { param([string]$Name) return (Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue) } function Register-LogonTask { param([string]$Name, [string]$Exe, [string]$Arguments, [switch]$Elevated) $action = New-ScheduledTaskAction -Execute $Exe -Argument $Arguments $trigger = New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME" $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) $level = if ($Elevated) { 'Highest' } else { 'Limited' } $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel $level Register-ScheduledTask -TaskName $Name -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null } function Unregister-LogonTask { param([string]$Name) Unregister-ScheduledTask -TaskName $Name -Confirm:$false -ErrorAction SilentlyContinue } function Invoke-Restart { Restart-Computer -Force } function Read-Answer { param([string]$Prompt) return (Read-Host $Prompt) } function Save-Download { param([string]$Url, [string]$Path) Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Path } # ---- helpers --------------------------------------------------------------------------------------------------------------------- function Say { param([string]$Text) Write-Information $Text } function Step { param([string]$Text) Write-Information ''; Write-Information "== $Text" } function Fail { param([string]$Text) throw [System.Exception]::new("setup-windows.ps1: $Text") } function Get-State { $f = Join-Path (Get-DataDir) 'state.json' if (Test-Path $f) { return (Get-Content -Raw $f | ConvertFrom-Json) } return [pscustomobject]@{ version = $SetupVersion; createdDistro = $false; wslconfig = @(); winget = @() } } function Save-State { param($State) if ($DryRun) { return } $d = Get-DataDir if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null } Protect-DataDir $d $State | ConvertTo-Json -Depth 5 | Set-Content -Encoding UTF8 (Join-Path $d 'state.json') } # .wslconfig: set keys of one section, keep everything else; returns the lines function Merge-IniKey { param([string[]]$Lines, [string]$Section, [hashtable]$Keys) $out = New-Object System.Collections.Generic.List[string] $in = $false; $seen = $false; $done = @{} foreach ($l in $Lines) { if ($l -match '^\s*\[(.+)\]\s*$') { if ($in) { foreach ($k in $Keys.Keys) { if (-not $done[$k]) { $out.Add("$k=$($Keys[$k])"); $done[$k] = $true } } } $in = ($Matches[1] -eq $Section); if ($in) { $seen = $true } $out.Add($l); continue } if ($in -and $l -match '^\s*([A-Za-z0-9_.]+)\s*=') { $k = $Matches[1] if ($Keys.ContainsKey($k)) { if (-not $done[$k]) { $out.Add("$k=$($Keys[$k])"); $done[$k] = $true }; continue } } $out.Add($l) } if ($in) { foreach ($k in $Keys.Keys) { if (-not $done[$k]) { $out.Add("$k=$($Keys[$k])"); $done[$k] = $true } } } if (-not $seen) { $out.Add("[$Section]"); foreach ($k in $Keys.Keys) { $out.Add("$k=$($Keys[$k])") } } return , $out.ToArray() } function Get-IniValue { param([string[]]$Lines, [string]$Section, [string]$Key) $in = $false foreach ($l in $Lines) { if ($l -match '^\s*\[(.+)\]\s*$') { $in = ($Matches[1] -eq $Section); continue } if ($in -and $l -match "^\s*$([regex]::Escape($Key))\s*=\s*(.*?)\s*$") { return $Matches[1] } } return $null } function Clear-IniKey { param([string[]]$Lines, [string]$Section, [string[]]$Keys) $in = $false $out = foreach ($l in $Lines) { if ($l -match '^\s*\[(.+)\]\s*$') { $in = ($Matches[1] -eq $Section); $l; continue } if ($in -and $l -match '^\s*([A-Za-z0-9_.]+)\s*=' -and $Keys -contains $Matches[1]) { continue } $l } return , @($out) } function Get-WslSetting { $mem = [math]::Max(2, [int][math]::Floor((Get-TotalMemoryGB) * 3 / 4)); return [ordered]@{ networkingMode = 'mirrored'; vmIdleTimeout = '-1'; memory = "$($mem)GB" } } function Test-WslInstalled { $r = Invoke-Wsl @('--status'); return ($r.Code -eq 0) } function Test-DistroInstalled { $r = Invoke-Wsl @('--list', '--quiet'); return ($r.Code -eq 0 -and (($r.Out -split "`r?`n") | ForEach-Object { $_.Trim([char]0, ' ') }) -contains $Distro) } function Test-Systemd { $r = Invoke-Wsl @('-d', $Distro, '-u', 'root', '--exec', 'sh', '-c', 'grep -qx "systemd=true" /etc/wsl.conf'); return ($r.Code -eq 0) } function Test-WslConfigOk { $f = Get-WslConfigPath if (-not (Test-Path $f)) { return $false } $lines = @(Get-Content $f) return ((Get-IniValue $lines 'wsl2' 'networkingMode') -eq 'mirrored' -and (Get-IniValue $lines 'wsl2' 'vmIdleTimeout') -eq '-1') } # setup-linux.sh beside this file, else from the site; LF line ends whatever git or a download did to it function Get-LinuxScript { $dst = Join-Path (Get-DataDir) 'setup-linux.sh' $src = if ($PSScriptRoot) { Join-Path $PSScriptRoot 'setup-linux.sh' } else { '' } if (-not $DryRun) { if (-not (Test-Path (Get-DataDir))) { New-Item -ItemType Directory -Path (Get-DataDir) -Force | Out-Null } Protect-DataDir (Get-DataDir) } if (-not ($src -and (Test-Path $src))) { $src = Join-Path (Get-DataDir) 'setup-linux.download' Say "setup-linux.sh is not beside this script: downloading $Site/worker/setup-linux.sh" if (-not $DryRun) { Save-Download "$Site/worker/setup-linux.sh" $src } } if (-not $DryRun) { $text = [System.IO.File]::ReadAllText($src) -replace "`r`n", "`n" [System.IO.File]::WriteAllText($dst, $text, (New-Object System.Text.UTF8Encoding $false)) } return $dst } function ConvertTo-WslPath { param([string]$Path) $p = $Path -replace '\\', '/'; if ($p -match '^([A-Za-z]):/(.*)$') { return "/mnt/$($Matches[1].ToLower())/$($Matches[2])" } return $p } function Get-ResumeArgument { $a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$(Join-Path (Get-DataDir) 'setup-windows.ps1')`"", '-Resume', '-Distro', $Distro, '-SshPort', "$SshPort") if ($Native) { $a += '-Native' } return ($a -join ' ') } # ---- -Native --------------------------------------------------------------------------------------------------------------------- $NativeParts = @( @{ Name = 'git'; Id = 'Git.Git'; Test = { Test-Command 'git.exe' }; Args = @() }, @{ Name = 'build tools'; Id = 'Microsoft.VisualStudio.2022.BuildTools'; Test = { (Test-Command 'cl.exe') -or (Test-Path "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC") }; Args = @('--override', '--quiet --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended') }, @{ Name = 'rustup'; Id = 'Rustlang.Rustup'; Test = { Test-Command 'rustup.exe' }; Args = @() }, @{ Name = 'node'; Id = 'OpenJS.NodeJS.LTS'; Test = { (Test-Command 'node.exe') -and ((& node.exe --version) -eq "v$NodeVersion") }; Args = @('--version', $NodeVersion) } ) function Install-Native { param($State) Step 'the Windows toolchain (-Native)' foreach ($p in $NativeParts) { if (& $p.Test) { Say "$($p.Name): there"; continue } Say "$($p.Name): installing $($p.Id)" if ($DryRun) { Say "would run: winget install --id $($p.Id) $($p.Args -join ' ')"; continue } $r = Invoke-Winget (@('install', '--id', $p.Id, '--exact', '--silent', '--accept-package-agreements', '--accept-source-agreements') + $p.Args) if ($r.Code -ne 0) { Fail "winget could not install $($p.Id): $($r.Out.Trim())" } $State.winget = @($State.winget) + $p.Id } if (-not $DryRun) { $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') & rustup.exe toolchain install "$RustVersion-x86_64-pc-windows-msvc" --profile minimal -c clippy -c rustfmt if ($LASTEXITCODE -ne 0) { Fail "rustup could not install $RustVersion" } & rustup.exe default "$RustVersion-x86_64-pc-windows-msvc" | Out-Null & npm.cmd install -g "pnpm@$PnpmVersion" --no-fund --no-audit if ($LASTEXITCODE -ne 0) { Fail "npm could not install pnpm $PnpmVersion" } } } # ---- the steps ------------------------------------------------------------------------------------------------------------------- function Invoke-Check { function Write-CheckLine { param([bool]$Ok, [string]$Name, [string]$Have, [string]$Missing, [string]$Fix) if ($Ok) { Say (" [ok] {0,-12} {1}" -f $Name, $Have) } else { Say (" [missing] {0,-12} {1}`n fix: {2}" -f $Name, $Missing, $Fix); $script:checkBad = 1 } } $script:checkBad = 0 $build = Get-WinBuild Write-CheckLine ($build -ge 22621) 'windows' "build $build" "build ${build}: mirrored networking needs Windows 11 22H2 (22621) or newer" 'Windows Update' Write-CheckLine (Test-WslInstalled) 'wsl' 'WSL2' 'no WSL' 'run this script as Administrator' Write-CheckLine (Test-WslConfigOk) 'wslconfig' 'mirrored networking, never idles out' 'no mirrored networking in .wslconfig' 'run this script' $distro = Test-DistroInstalled Write-CheckLine $distro 'distro' $Distro "no $Distro" 'run this script' if ($distro) { Write-CheckLine (Test-Systemd) 'systemd' 'on' 'off in /etc/wsl.conf' 'run this script' } Write-CheckLine ([bool](Get-FwRule 'DIY-worker-ssh')) 'firewall' "port $SshPort open to WSL (the pairing port opens only while -Join waits)" 'no Hyper-V firewall rule' 'run this script as Administrator' Write-CheckLine ([bool](Get-Task $TaskKeep)) 'keep-alive' 'the distribution starts at your sign-in' 'no sign-in task' 'run this script' if ($Native) { foreach ($p in $NativeParts) { Write-CheckLine ([bool](& $p.Test)) $p.Name $p.Id "no $($p.Name)" 'run this script with -Native' } } if ($distro) { Say '' Say "Inside ${Distro}:" $code = Invoke-WslLive @('-d', $Distro, '-u', 'root', '--exec', 'bash', (ConvertTo-WslPath (Join-Path (Get-DataDir) 'setup-linux.sh')), '--check', '--ssh-port', "$SshPort") if ($code -ne 0) { $script:checkBad = 1 } } if ($script:checkBad -eq 0) { Say 'Everything is there.' } else { Say 'Something is missing: the fix is under each line.' } return $script:checkBad } function Invoke-Setup { $state = Get-State Step "DIY build machine set-up $SetupVersion" # 1. WSL if (-not (Test-WslInstalled)) { Step 'WSL2' if ($DryRun) { Say 'would run: wsl --install --no-distribution'; return 0 } $r = Invoke-Wsl @('--install', '--no-distribution') if ($r.Code -ne 0 -and $r.Out -notmatch 'restart|reboot|neu starten|red\u00e9marr') { Fail "wsl --install failed: $($r.Out.Trim())" } if (-not (Test-WslInstalled)) { # what the task runs after the restart: this script and setup-linux.sh, from the data folder [void](Get-LinuxScript) if (-not $PSCommandPath) { Fail 'run it from its file (powershell -File setup-windows.ps1): after the restart the task runs that file again' } Copy-Item -Force $PSCommandPath (Join-Path (Get-DataDir) 'setup-windows.ps1') Register-LogonTask -Name $TaskResume -Exe 'powershell.exe' -Arguments (Get-ResumeArgument) -Elevated $script:ResumeTaskSet = $true Say 'Windows needs one restart to finish WSL. This set-up carries on by itself when you sign in again.' if ((Read-Answer 'Restart now? (y/n)') -match '^[yY]') { Invoke-Restart } return 3 } } # 2. .wslconfig Step '.wslconfig: mirrored networking' $cfg = Get-WslConfigPath $lines = if (Test-Path $cfg) { @(Get-Content $cfg) } else { @() } $keys = Get-WslSetting $before = @{}; foreach ($k in $keys.Keys) { $before[$k] = Get-IniValue $lines 'wsl2' $k } $new = Merge-IniKey $lines 'wsl2' $keys if (($new -join "`n") -ne ($lines -join "`n")) { if ($DryRun) { Say "would write $cfg" } else { if (@($state.wslconfig).Count -eq 0) { $state.wslconfig = @($keys.Keys | ForEach-Object { [pscustomobject]@{ key = $_; was = $before[$_] } }) } Set-Content -Path $cfg -Value $new -Encoding ASCII Save-State $state [void](Invoke-Wsl @('--shutdown')) } } else { Say 'there' } # 3. the distribution Step "the distribution: $Distro" if (-not (Test-DistroInstalled)) { if ($DryRun) { Say "would run: wsl --install -d $Distro --no-launch" } else { $r = Invoke-Wsl @('--install', '-d', $Distro, '--no-launch') if ($r.Code -ne 0) { Fail "could not install ${Distro}: $($r.Out.Trim())" } $state.createdDistro = $true; Save-State $state } } else { Say 'there' } if (-not $DryRun -and -not (Test-Systemd)) { $r = Invoke-Wsl @('-d', $Distro, '-u', 'root', '--exec', 'sh', '-c', 'touch /etc/wsl.conf && if grep -q "^\[boot\]" /etc/wsl.conf; then sed -i "/^\[boot\]/a systemd=true" /etc/wsl.conf; else printf "\n[boot]\nsystemd=true\n" >> /etc/wsl.conf; fi') if ($r.Code -ne 0) { Fail "could not turn systemd on in ${Distro}: $($r.Out.Trim())" } [void](Invoke-Wsl @('--terminate', $Distro)) } # 4. the firewall, inbound to WSL only Step "Hyper-V firewall: port $SshPort to WSL" if (-not (Get-FwRule 'DIY-worker-ssh')) { $remote = Get-RemoteRange if ($DryRun) { Say "would add the rule DIY-worker-ssh for port $SshPort from $remote" } else { Add-FwRule -Name 'DIY-worker-ssh' -Port $SshPort -Remote $remote } } # 5. inside Step "setup-linux.sh inside $Distro" $sh = Get-LinuxScript $linuxArgs = @('-d', $Distro, '-u', 'root', '--exec', 'bash', (ConvertTo-WslPath $sh), '--ssh-port', "$SshPort") if ($DryRun) { $linuxArgs += '--dry-run' } $code = Invoke-WslLive $linuxArgs if ($code -ne 0) { Fail "setup-linux.sh stopped inside $Distro (exit $code): the lines above say why" } # 6. keep it running while you are signed in if (-not (Get-Task $TaskKeep)) { if ($DryRun) { Say "would add the sign-in task '$TaskKeep'" } else { # conhost --headless: no console window at every sign-in Register-LogonTask -Name $TaskKeep -Exe 'conhost.exe' -Arguments "--headless wsl.exe -d $Distro -u root --exec /bin/sh -c `"exec sleep infinity`"" } } if ($Native) { Install-Native $state } if (Get-Task $TaskResume) { Unregister-LogonTask $TaskResume } # a copy that stays, for -Join, -Check and -Remove later (diy-setup.ps1 -BuildMachine runs this from a folder it deletes) $kept = Join-Path (Get-DataDir) 'setup-windows.ps1' if (-not $DryRun -and $PSCommandPath -and $PSCommandPath -ne $kept) { Copy-Item -Force $PSCommandPath $kept } Save-State $state Step 'done' if ($Join) { return (Invoke-Join) } Say "This computer is ready. To join it to your DIY: on your DIY's computer run diy worker add " Say ' and then here: setup-windows.ps1 -Join' return 0 } function Invoke-Join { Step 'join this computer to your DIY' if (-not (Test-DistroInstalled)) { Fail "no $Distro yet: run this script without -Join first" } $a = @('-d', $Distro, '-u', 'root', '--exec', 'bash', (ConvertTo-WslPath (Join-Path (Get-DataDir) 'setup-linux.sh')), '--join') if ($Code) { $a += $Code } $a += @('--ssh-port', "$SshPort") # the pairing port is open for the wait only, and closed however it ends if (-not $DryRun -and -not (Get-FwRule 'DIY-worker-pair')) { Add-FwRule -Name 'DIY-worker-pair' -Port $PairPort -Remote (Get-RemoteRange) } try { return (Invoke-WslLive $a) } finally { if (-not $DryRun) { Unregister-FwRule 'DIY-worker-pair' } } } function Invoke-Remove { $state = Get-State Step 'remove the DIY build machine' if (-not $Yes) { $what = if ($state.createdDistro) { "the $Distro distribution with everything in it" } else { "the diy-worker user and its tools inside $Distro" } if ((Read-Answer "This deletes $what, the firewall rules, the sign-in task and the .wslconfig settings this script set. Type yes") -ne 'yes') { Say 'nothing removed'; return 1 } } if (Test-DistroInstalled) { if ($state.createdDistro) { if ($DryRun) { Say "would run: wsl --unregister $Distro" } else { [void](Invoke-Wsl @('--unregister', $Distro)); Say "$Distro`: removed" } } else { $sh = Join-Path (Get-DataDir) 'setup-linux.sh' if (Test-Path $sh) { [void](Invoke-WslLive @('-d', $Distro, '-u', 'root', '--exec', 'bash', (ConvertTo-WslPath $sh), '--remove', '--yes')) Say "$Distro was there before: only what setup-linux.sh did inside it is removed" } else { Say "$Distro was there before, and this script has no copy of setup-linux.sh any more: nothing inside it was changed. To take the build machine out of it: setup-linux.sh --remove inside $Distro, as root" } } } foreach ($n in @('DIY-worker-ssh', 'DIY-worker-pair')) { if (-not $DryRun) { Unregister-FwRule $n } } foreach ($t in @($TaskKeep, $TaskResume)) { if (-not $DryRun) { Unregister-LogonTask $t } } $cfg = Get-WslConfigPath if ((Test-Path $cfg) -and @($state.wslconfig).Count -gt 0 -and -not $DryRun) { $lines = @(Get-Content $cfg) $restore = @{}; $drop = @() foreach ($e in $state.wslconfig) { if ($null -ne $e.was -and "$($e.was)" -ne '') { $restore[$e.key] = $e.was } else { $drop += $e.key } } $lines = Clear-IniKey $lines 'wsl2' $drop if ($restore.Count -gt 0) { $lines = Merge-IniKey $lines 'wsl2' $restore } Set-Content -Path $cfg -Value $lines -Encoding ASCII Say '.wslconfig: the settings this script changed are as they were' } foreach ($id in @($state.winget)) { if ($id -and -not $DryRun) { [void](Invoke-Winget @('uninstall', '--id', $id, '--exact', '--silent')) } } if (-not $DryRun) { Remove-Item -Recurse -Force (Get-DataDir) -ErrorAction SilentlyContinue } Say 'Done. WSL itself stays installed (other things may use it): wsl --uninstall removes it.' return 0 } function Invoke-Main { if ($Check -and $Remove) { Say 'setup-windows.ps1: -Check and -Remove do not go together'; return 2 } if ($SshPort -lt 1 -or $SshPort -gt 65535) { Say 'setup-windows.ps1: -SshPort is a port'; return 2 } if ($Distro -notmatch '^[A-Za-z0-9._-]{1,64}$') { Say 'setup-windows.ps1: -Distro is a distribution name, like Ubuntu-24.04'; return 2 } if ($Code -and (($Code.ToUpper() -replace '[^0-9A-Z]', '').Length -ne 12)) { Say 'setup-windows.ps1: a code is 12 letters and digits, like ABCD-EFGH-JKMN'; return 2 } try { if ($Check) { return (Invoke-Check) } if (-not $DryRun -and -not (Test-Admin)) { Say 'setup-windows.ps1: run it in PowerShell as Administrator (right-click PowerShell, Run as administrator)'; return 1 } $build = Get-WinBuild if ($build -lt 22621) { Say "setup-windows.ps1: this is Windows build $build; a build machine needs Windows 11 22H2 (build 22621) or newer, for WSL's mirrored networking. Windows Update brings it."; return 1 } if ($Remove) { return (Invoke-Remove) } if ($Join -and -not $Resume -and (Test-DistroInstalled) -and (Test-Systemd)) { return (Invoke-Join) } return (Invoke-Setup) } catch { Say $_.Exception.Message return 1 } finally { # A resumed run removes its sign-in task whatever happened, so an elevated PowerShell does not start at every sign-in (51.40 review 1), # unless this run set it again for one more restart (51.40 review 2, N3) if ($Resume -and -not $DryRun -and -not $script:ResumeTaskSet -and (Get-Task $TaskResume)) { Unregister-LogonTask $TaskResume Say "The set-up after the restart has ended. If it says above that something failed, run it again yourself: powershell -ExecutionPolicy Bypass -File `"$(Join-Path (Get-DataDir) 'setup-windows.ps1')`"" } } } if ($env:DIY_WORKER_PS_TEST -eq '1') { return } exit (Invoke-Main)