]> vilimpoc.org git repositories - dotfiles/blob - setup-windows-with-uac.ps1
dotfiles: put vswhere.exe on the user PATH
[dotfiles] / setup-windows-with-uac.ps1
1 #Requires -RunAsAdministrator\r
2 <#\r
3   setup-windows-with-uac.ps1\r
4   Elevated portion of the Windows provisioning. Invoked by setup-windows.bat\r
5   via Start-Process -Verb RunAs, or run manually from an Administrator prompt.\r
6 \r
7   What this installs / configures:\r
8     - OpenSSH Client capability (the ssh.exe rsync shells out to, and the\r
9       System32 libcrypto.dll the release's own ssh.exe links against)\r
10     - ssh-agent set to automatic + started\r
11     - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22\r
12     - rsync for Windows (nuket/rsync-windows) in C:\Tools\rsync, on the machine\r
13       PATH: rsync.exe plus the ssh.exe it runs, out of the release zip for this\r
14       architecture\r
15     - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,\r
16       Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)\r
17     - Windows Driver Kit 10.0.26100\r
18 \r
19   Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r
20     Professional : https://aka.ms/vs/17/release/vs_professional.exe\r
21     Enterprise   : https://aka.ms/vs/17/release/vs_enterprise.exe\r
22 #>\r
23 \r
24 $ErrorActionPreference = 'Stop'\r
25 \r
26 function Write-Step([string]$Msg) {\r
27     Write-Host "`n==> $Msg" -ForegroundColor Cyan\r
28 }\r
29 \r
30 function Assert-ExitCode([int]$Code, [string]$Step) {\r
31     # 0 = success, 3010 = success + reboot required\r
32     if ($Code -notin @(0, 3010)) {\r
33         throw "$Step failed with exit code $Code"\r
34     }\r
35     if ($Code -eq 3010) {\r
36         Write-Host "    [reboot required after $Step]" -ForegroundColor Yellow\r
37     }\r
38 }\r
39 \r
40 function Show-VsSetupLogs {\r
41     # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because\r
42     # this script runs elevated, that %TEMP% belongs to the elevated user and is\r
43     # readable here even when it is NOT readable by the non-elevated caller. Fold\r
44     # only the NEWEST installer + bootstrapper log into the transcript (the setup\r
45     # engine log is where per-component / product errors actually appear) and\r
46     # keep it short so the transcript stays readable.\r
47     Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan\r
48     $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |\r
49               Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }\r
50     $picks = @()\r
51     $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*'    } | Sort-Object LastWriteTime | Select-Object -Last 1\r
52     $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r
53     $picks = $picks | Where-Object { $_ }\r
54     if (-not $picks) {\r
55         Write-Host '    (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow\r
56         return\r
57     }\r
58     foreach ($l in $picks) {\r
59         Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow\r
60         Get-Content $l.FullName -Tail 40\r
61     }\r
62 }\r
63 \r
64 function Invoke-VsModify {\r
65     # Run one VS install/modify pass for a named group of components. Splitting\r
66     # the install into separate passes makes it obvious WHICH group fails: each\r
67     # call prints its label and exit code before Assert-ExitCode throws.\r
68     param(\r
69         [string]   $Label,\r
70         [string[]] $Ids\r
71     )\r
72     Write-Step "VS2022: $Label"\r
73     $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '\r
74     # --installPath must be quoted: it contains spaces ("C:\Program Files\...").\r
75     # Windows PowerShell 5.1's Start-Process does not quote array elements, so we\r
76     # hand-build a single string. Component IDs / flags have no spaces.\r
77     $common = '--includeRecommended --quiet --norestart --wait'\r
78     if ($script:InstallPath) {\r
79         $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"\r
80     } else {\r
81         # No existing install yet -> this first pass performs the base install.\r
82         $argString = "$addStr $common"\r
83     }\r
84     Write-Host "    > $script:VsBootstrapper $argString" -ForegroundColor DarkGray\r
85     $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow\r
86     Write-Host "    exit code: $($p.ExitCode)"\r
87     Assert-ExitCode $p.ExitCode "VS2022 ($Label)"\r
88 \r
89     # After the first (fresh) install, re-detect the install path so subsequent\r
90     # passes use `modify`.\r
91     if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {\r
92         $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |\r
93                               Select-Object -First 1\r
94     }\r
95 }\r
96 \r
97 # ---------------------------------------------------------------------------\r
98 # This runs in a separate elevated window that closes the moment it exits, so\r
99 # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror\r
100 # all output to a log next to the script and exit with a real code so the\r
101 # caller can detect success/failure and show the log.\r
102 # ---------------------------------------------------------------------------\r
103 $LogFile  = Join-Path $PSScriptRoot 'setup-windows-uac.log'\r
104 $ExitCode = 0\r
105 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}\r
106 \r
107 try {\r
108 \r
109 # ---------------------------------------------------------------------------\r
110 # Base tools via winget\r
111 # ---------------------------------------------------------------------------\r
112 \r
113 # ---------------------------------------------------------------------------\r
114 # OpenSSH Client\r
115 #\r
116 # Present by default on Windows 10 1809+ / Windows 11, but removable, and absent\r
117 # from some Server images. Two things below want it: rsync does not speak ssh\r
118 # itself, it execs an ssh binary, and the release's own ssh.exe links against the\r
119 # libcrypto.dll this capability puts in System32. It also owns the ssh-agent\r
120 # service configured next, so a missing client is why that step would fail.\r
121 #\r
122 # Non-fatal, like the server half below: a box that cannot have it should still\r
123 # finish provisioning.\r
124 # ---------------------------------------------------------------------------\r
125 Write-Step 'OpenSSH Client'\r
126 try {\r
127     $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |\r
128             Select-Object -First 1\r
129     if (-not $sshc) {\r
130         Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'\r
131     } elseif ($sshc.State -eq 'Installed') {\r
132         Write-Host "    OK: $($sshc.Name) already installed"\r
133     } else {\r
134         Write-Host "    Installing $($sshc.Name) ..."\r
135         $r = Add-WindowsCapability -Online -Name $sshc.Name\r
136         if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Client]' -ForegroundColor Yellow }\r
137     }\r
138 } catch {\r
139     Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"\r
140 }\r
141 \r
142 # ---------------------------------------------------------------------------\r
143 # SSH agent\r
144 # ---------------------------------------------------------------------------\r
145 Write-Step 'Enabling ssh-agent'\r
146 Set-Service -Name ssh-agent -StartupType Automatic\r
147 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }\r
148 \r
149 # ---------------------------------------------------------------------------\r
150 # OpenSSH Server (sshd)\r
151 #\r
152 # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the\r
153 # transport rsync rides on when seeding test data in. Ships with Windows 10\r
154 # 1809+ / Windows 11 as an on-demand capability, so no third-party install.\r
155 #\r
156 # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall\r
157 # rule; we verify and create it if missing (it is absent on some images).\r
158 #\r
159 # Non-fatal: a box that can't run sshd should still finish provisioning.\r
160 # ---------------------------------------------------------------------------\r
161 Write-Step 'OpenSSH Server (sshd)'\r
162 try {\r
163     $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |\r
164             Select-Object -First 1\r
165     if (-not $sshd) {\r
166         Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'\r
167     } else {\r
168         if ($sshd.State -ne 'Installed') {\r
169             Write-Host "    Installing $($sshd.Name) ..."\r
170             $r = Add-WindowsCapability -Online -Name $sshd.Name\r
171             if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Server]' -ForegroundColor Yellow }\r
172         } else {\r
173             Write-Host "    OK: $($sshd.Name) already installed"\r
174         }\r
175 \r
176         Set-Service -Name sshd -StartupType Automatic\r
177         if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }\r
178         Write-Host '    sshd: Automatic + running'\r
179 \r
180         # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and\r
181         # bridged adapters are frequently classified Public, and the capability's\r
182         # own rule is Private-only on some images, which is what leaves a plainly\r
183         # running sshd plainly unreachable.\r
184         #\r
185         # OpenSSH-Server-In-TCP is the name the capability itself uses, so this\r
186         # WIDENS that rule rather than adding a second one next to it. Creating\r
187         # our own under a different name would leave the narrow rule in place and\r
188         # the box still unreachable on a Public-classified adapter; creating one\r
189         # under the same name would collide. Adopt it if present, create it if not.\r
190         $ruleName = 'OpenSSH-Server-In-TCP'\r
191         if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {\r
192             Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any\r
193             Write-Host "    Widened firewall rule $ruleName to all profiles"\r
194         } else {\r
195             New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `\r
196                 -Enabled True -Direction Inbound -Protocol TCP -Action Allow `\r
197                 -LocalPort 22 -Profile Any | Out-Null\r
198             Write-Host "    Added firewall rule $ruleName (TCP 22, all profiles)"\r
199         }\r
200     }\r
201 } catch {\r
202     Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"\r
203 }\r
204 \r
205 # ---------------------------------------------------------------------------\r
206 # rsync for Windows (github.com/nuket/rsync-windows)\r
207 #\r
208 # Windows' OpenSSH ships the transport only - no rsync - so pushing test data\r
209 # from a Linux box needs an rsync.exe on the Windows side.\r
210 #\r
211 # The release is one zip per architecture - rsync-windows-x64.zip and\r
212 # rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the\r
213 # licence texts under exactly those names. Both exes are installed, together:\r
214 # rsync.exe prefers an ssh.exe in its own directory, and the release's build is\r
215 # what makes a push FROM this box run at line rate. The ssh.exe Windows ships\r
216 # reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the\r
217 # link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same\r
218 # known_hosts - and a bare `ssh` still resolves to the in-box client, which sits\r
219 # ahead of C:\Tools\rsync on the machine PATH.\r
220 #\r
221 # That ssh.exe links against the libcrypto.dll the OpenSSH Client capability\r
222 # above puts in System32: Windows' own LibreSSL, and the fast one, since it uses\r
223 # AES-NI. No copy of it ships in the zip, so where the capability is missing we\r
224 # unpack rsync alone rather than an ssh.exe that will not start.\r
225 #\r
226 # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is\r
227 # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes\r
228 # the client-side --rsync-path escape hatch painful to quote. Added to the\r
229 # MACHINE PATH so it resolves for every account, including the non-interactive\r
230 # sshd session, which builds its environment from the machine + user registry\r
231 # PATH rather than from a login shell.\r
232 #\r
233 # Non-fatal: a download failure only warns.\r
234 # ---------------------------------------------------------------------------\r
235 Write-Step 'rsync for Windows'\r
236 $RsyncRepo  = 'nuket/rsync-windows'\r
237 $RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }\r
238 # The /releases/latest/download/ redirect rather than the API: unauthenticated\r
239 # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a\r
240 # shared NAT can genuinely exhaust, and the redirect costs none of that budget.\r
241 # To hold a box on a known build, pin the tag instead:\r
242 #     .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset\r
243 $RsyncUrl   = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"\r
244 $RsyncDir   = 'C:\Tools\rsync'\r
245 try {\r
246     New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null\r
247     $RsyncExe = Join-Path $RsyncDir 'rsync.exe'\r
248 \r
249     # Does the release's ssh.exe have the libcrypto it needs? Decided before the\r
250     # download so the answer can also gate what comes out of the zip.\r
251     $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'\r
252     $WantSsh   = Test-Path $SysCrypto\r
253     if (-not $WantSsh) {\r
254         Write-Warning "$SysCrypto is missing - the OpenSSH Client capability is not installed - and the release's ssh.exe needs it. Installing rsync.exe only; rsync will use the ssh on the PATH."\r
255     } else {\r
256         $v = (Get-Item $SysCrypto).VersionInfo.FileVersion\r
257         if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {\r
258             Write-Warning "$SysCrypto is LibreSSL $v; the release's ssh.exe is built against 3.8.2 (Windows OpenSSH Client 9.5). Update Windows, or expect ssh.exe not to start."\r
259         }\r
260     }\r
261 \r
262     # Download and unpack beside the targets, not over them, so an interrupted\r
263     # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch\r
264     # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive\r
265     # refuses any other extension outright ("*.download is not a supported\r
266     # archive file format"), where PowerShell 7 just reads the file.\r
267     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\r
268     $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"\r
269     Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing\r
270     Write-Host "    Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"\r
271 \r
272     # Verify against the .sha256 published beside it. Same origin, so this is an\r
273     # integrity check on the transfer rather than a defence against a hostile\r
274     # release - but a truncated or proxy-mangled download is the failure that\r
275     # actually happens, and it fails here instead of mid-transfer later.\r
276     #\r
277     # -OutFile, not .Content: GitHub serves the .sha256 as\r
278     # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather\r
279     # than a string for any non-text content type, so .Content would compare the\r
280     # first BYTE against the hash and fail on every correct download.\r
281     $tmpSha = "$tmpZip.sha256"\r
282     Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing\r
283     $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()\r
284     Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue\r
285     $got  = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()\r
286     if ($want -and $want -ne $got) {\r
287         Remove-Item $tmpZip -Force\r
288         throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"\r
289     }\r
290     Write-Host "    SHA-256 verified: $got"\r
291 \r
292     # Unpack to a scratch directory and move out the files we asked for, rather\r
293     # than expanding straight over the install directory: the zip is the unit\r
294     # that was checksummed, and this way a future release adding something to it\r
295     # cannot quietly drop that something onto the machine PATH.\r
296     $unpack = Join-Path $RsyncDir '.unpack'\r
297     if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }\r
298     Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force\r
299     Remove-Item $tmpZip -Force\r
300     foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {\r
301         $src = Join-Path $unpack $f\r
302         if (-not (Test-Path $src)) { continue }\r
303         if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }\r
304         Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force\r
305     }\r
306     Remove-Item -Recurse -Force $unpack\r
307     Write-Host "    Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"\r
308 \r
309     # Machine PATH (HKLM environment). Idempotent: only appends if absent.\r
310     $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
311     if (-not $m) { $m = '' }\r
312     if (($m -split ';') -notcontains $RsyncDir) {\r
313         $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }\r
314         [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
315         Write-Host "    Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."\r
316         # sshd caches the environment it was started with, so an already-running\r
317         # service would not see the new PATH until restarted.\r
318         if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {\r
319             Restart-Service sshd\r
320             Write-Host '    Restarted sshd so it inherits the updated machine PATH.'\r
321         }\r
322     } else {\r
323         Write-Host "    OK: $RsyncDir already in the machine PATH"\r
324     }\r
325 \r
326     & $RsyncExe --version | Select-Object -First 1\r
327 } catch {\r
328     Write-Warning "rsync install failed: $($_.Exception.Message)"\r
329     Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"\r
330     Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."\r
331 }\r
332 \r
333 # ---------------------------------------------------------------------------\r
334 # Visual Studio 2022 Community\r
335 # ---------------------------------------------------------------------------\r
336 $TempDir = Join-Path $env:TEMP 'dev_install'\r
337 New-Item -ItemType Directory -Force -Path $TempDir | Out-Null\r
338 \r
339 # Component IDs split into independent groups so each can be installed in its\r
340 # own pass. The base group is the known-good set; Clang and the Windows XP\r
341 # toolset are layered on afterwards so a failure clearly identifies the culprit.\r
342 # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community\r
343 $BaseComponents = @(\r
344     # Core C++ desktop workload\r
345     'Microsoft.VisualStudio.Workload.NativeDesktop'\r
346 \r
347     # Spectre-mitigated MSVC runtime libs\r
348     'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'\r
349     'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'\r
350 \r
351     # Spectre-mitigated ATL (needed for many driver/COM projects)\r
352     'Microsoft.VisualStudio.Component.VC.ATL.Spectre'\r
353 \r
354     # Windows 11 SDK — build number must match the WDK below\r
355     'Microsoft.VisualStudio.Component.Windows11SDK.26100'\r
356 \r
357     # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT\r
358     # install this (it only prompts interactively), so it must be added here.\r
359     'Component.Microsoft.Windows.DriverKit'\r
360 )\r
361 \r
362 # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang\r
363 # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.\r
364 $ClangComponents = @(\r
365     'Microsoft.VisualStudio.Component.VC.Llvm.Clang'\r
366     'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'\r
367 )\r
368 \r
369 # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141\r
370 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;\r
371 # WinXP layers the XP-compatible CRT/SDK on top of it.\r
372 $XpComponents = @(\r
373     'Microsoft.VisualStudio.Component.VC.v141.x86.x64'\r
374     'Microsoft.VisualStudio.Component.WinXP'\r
375 )\r
376 \r
377 # Detect an existing VS install via vswhere (ships with the VS Installer).\r
378 # These are referenced by Invoke-VsModify via $script: scope.\r
379 $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'\r
380 $InstallPath = $null\r
381 if (Test-Path $VsWhere) {\r
382     $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
383                    Select-Object -First 1\r
384 }\r
385 \r
386 Write-Step 'Downloading VS2022 Community bootstrapper'\r
387 $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'\r
388 $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'\r
389 Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing\r
390 \r
391 # Install in three sequential passes. The base set is installed first (this is\r
392 # the configuration that previously worked); Clang and the XP toolset are added\r
393 # afterwards. If one fails, its label pinpoints which group is responsible.\r
394 Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents\r
395 Invoke-VsModify -Label 'Clang / LLVM'            -Ids $ClangComponents\r
396 Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents\r
397 \r
398 # ---------------------------------------------------------------------------\r
399 # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped\r
400 # it and the failure only surfaced at build time, so check on disk and fail\r
401 # loudly here instead.\r
402 # ---------------------------------------------------------------------------\r
403 Write-Step 'Verifying v141 / XP toolset'\r
404 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
405                Select-Object -First 1\r
406 $V141 = if ($InstallPath) {\r
407     Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |\r
408         Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1\r
409 }\r
410 if ($V141) {\r
411     Write-Host "    OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green\r
412 } else {\r
413     Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'\r
414     Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'\r
415     Write-Warning '  - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'\r
416     Write-Warning '  - C++ Windows XP Support for VS 2017 (v141) tools'\r
417 }\r
418 \r
419 # ---------------------------------------------------------------------------\r
420 # Windows Driver Kit (WDK 10.0.26100)\r
421 # Build 26100 matches the Windows 11 SDK installed above.\r
422 # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.\r
423 # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").\r
424 # ---------------------------------------------------------------------------\r
425 $WdkVersion = '10.0.26100'\r
426 $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `\r
427                         -ErrorAction SilentlyContinue).WdkBinRootVersioned\r
428 \r
429 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {\r
430     # Re-running wdksetup.exe for an already-present version returns exit code\r
431     # 2008 (maintenance mode / nothing to do), which is not a real failure.\r
432     Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"\r
433 } else {\r
434     Write-Step 'Downloading WDK installer'\r
435     $WdkUrl       = 'https://go.microsoft.com/fwlink/?linkid=2335869'\r
436     $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'\r
437     Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing\r
438 \r
439     Write-Step 'Installing WDK'\r
440     $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow\r
441     Write-Host "    WDK installer exit code: $($proc.ExitCode)"\r
442     if ($proc.ExitCode -eq 2008) {\r
443         # 2008 = the WDK is already present; the installer has nothing to do.\r
444         Write-Host '    [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow\r
445     } else {\r
446         Assert-ExitCode $proc.ExitCode 'WDK'\r
447     }\r
448 }\r
449 \r
450 # ---------------------------------------------------------------------------\r
451 # Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling,\r
452 # used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature\r
453 # that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it.\r
454 # The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it\r
455 # is the most reliable source. Idempotent (skips if xperf is already present in\r
456 # either the SDK or ADK location) and non-fatal so it never aborts provisioning.\r
457 # Lighter alternative if you don't want the full ADK: install the Windows SDK's\r
458 # "Windows Performance Toolkit" optional feature via winsdksetup.exe /features\r
459 # OptionId.WindowsPerformanceToolkit.\r
460 # ---------------------------------------------------------------------------\r
461 Write-Step 'Windows Performance Toolkit (xperf / WPA)'\r
462 $wptRoots = @(\r
463     (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
464     (Join-Path $env:ProgramFiles          'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
465     (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe')\r
466 )\r
467 $xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1\r
468 if ($xperf) {\r
469     Write-Host "    OK: WPT already present ($xperf)" -ForegroundColor Green\r
470 } else {\r
471     try {\r
472         winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r
473             --accept-source-agreements --accept-package-agreements\r
474         Write-Host '    Windows ADK (includes Windows Performance Toolkit) installed.'\r
475     } catch {\r
476         Write-Warning "WPT install failed: $($_.Exception.Message)"\r
477         Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r
478         Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'\r
479     }\r
480 }\r
481 \r
482 # ---------------------------------------------------------------------------\r
483 Write-Host "`nAll done." -ForegroundColor Green\r
484 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r
485 \r
486 }\r
487 catch {\r
488     $ExitCode = 1\r
489     Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red\r
490     if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }\r
491     # Only fold in the VS Installer logs when a VS step actually failed; for other\r
492     # steps (e.g. WDK) those logs are stale and misleading, so the message above\r
493     # is what matters.\r
494     if ($_.Exception.Message -match 'VS2022') {\r
495         try { Show-VsSetupLogs } catch {}\r
496     }\r
497 }\r
498 finally {\r
499     try { Stop-Transcript | Out-Null } catch {}\r
500 \r
501     # This log was created by the elevated (admin) process, so by default the\r
502     # non-elevated caller can't delete it (their token has Administrators marked\r
503     # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs\r
504     # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known\r
505     # Users SID, used here so this is locale-independent.\r
506     try {\r
507         if (Test-Path $LogFile) {\r
508             $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')\r
509             $acl  = Get-Acl -Path $LogFile\r
510             $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(\r
511                         $usersSid, 'Modify', 'Allow')\r
512             $acl.AddAccessRule($rule)\r
513             Set-Acl -Path $LogFile -AclObject $acl\r
514         }\r
515     } catch {\r
516         Write-Host "    [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow\r
517     }\r
518 }\r
519 \r
520 exit $ExitCode\r