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