]> vilimpoc.org git repositories - dotfiles/blame - setup-windows-with-uac.ps1
dotfiles: Linux dev-box provisioning script
[dotfiles] / setup-windows-with-uac.ps1
CommitLineData
3c096107
MV
1#Requires -RunAsAdministrator\r
2<#\r
3 setup-windows-with-uac.ps1\r
4 Elevated portion of BlockBox 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 - ssh-agent set to automatic + started\r
9 - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,\r
10 Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)\r
11 - Windows Driver Kit 10.0.26100\r
12\r
13 Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r
14 Professional : https://aka.ms/vs/17/release/vs_professional.exe\r
15 Enterprise : https://aka.ms/vs/17/release/vs_enterprise.exe\r
16#>\r
17\r
18$ErrorActionPreference = 'Stop'\r
19\r
20function Write-Step([string]$Msg) {\r
21 Write-Host "`n==> $Msg" -ForegroundColor Cyan\r
22}\r
23\r
24function Assert-ExitCode([int]$Code, [string]$Step) {\r
25 # 0 = success, 3010 = success + reboot required\r
26 if ($Code -notin @(0, 3010)) {\r
27 throw "$Step failed with exit code $Code"\r
28 }\r
29 if ($Code -eq 3010) {\r
30 Write-Host " [reboot required after $Step]" -ForegroundColor Yellow\r
31 }\r
32}\r
33\r
34function Show-VsSetupLogs {\r
35 # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because\r
36 # this script runs elevated, that %TEMP% belongs to the elevated user and is\r
37 # readable here even when it is NOT readable by the non-elevated caller. Fold\r
38 # only the NEWEST installer + bootstrapper log into the transcript (the setup\r
39 # engine log is where per-component / product errors actually appear) and\r
40 # keep it short so the transcript stays readable.\r
41 Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan\r
42 $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |\r
43 Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }\r
44 $picks = @()\r
45 $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r
46 $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r
47 $picks = $picks | Where-Object { $_ }\r
48 if (-not $picks) {\r
49 Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow\r
50 return\r
51 }\r
52 foreach ($l in $picks) {\r
53 Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow\r
54 Get-Content $l.FullName -Tail 40\r
55 }\r
56}\r
57\r
58function Invoke-VsModify {\r
59 # Run one VS install/modify pass for a named group of components. Splitting\r
60 # the install into separate passes makes it obvious WHICH group fails: each\r
61 # call prints its label and exit code before Assert-ExitCode throws.\r
62 param(\r
63 [string] $Label,\r
64 [string[]] $Ids\r
65 )\r
66 Write-Step "VS2022: $Label"\r
67 $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '\r
68 # --installPath must be quoted: it contains spaces ("C:\Program Files\...").\r
69 # Windows PowerShell 5.1's Start-Process does not quote array elements, so we\r
70 # hand-build a single string. Component IDs / flags have no spaces.\r
71 $common = '--includeRecommended --quiet --norestart --wait'\r
72 if ($script:InstallPath) {\r
73 $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"\r
74 } else {\r
75 # No existing install yet -> this first pass performs the base install.\r
76 $argString = "$addStr $common"\r
77 }\r
78 Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray\r
79 $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow\r
80 Write-Host " exit code: $($p.ExitCode)"\r
81 Assert-ExitCode $p.ExitCode "VS2022 ($Label)"\r
82\r
83 # After the first (fresh) install, re-detect the install path so subsequent\r
84 # passes use `modify`.\r
85 if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {\r
86 $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |\r
87 Select-Object -First 1\r
88 }\r
89}\r
90\r
91# ---------------------------------------------------------------------------\r
92# This runs in a separate elevated window that closes the moment it exits, so\r
93# the non-elevated caller (setup-windows.bat) can't see what happened. Mirror\r
94# all output to a log next to the script and exit with a real code so the\r
95# caller can detect success/failure and show the log.\r
96# ---------------------------------------------------------------------------\r
97$LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log'\r
98$ExitCode = 0\r
99try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}\r
100\r
101try {\r
102\r
103# ---------------------------------------------------------------------------\r
104# Base tools via winget\r
105# ---------------------------------------------------------------------------\r
106# ---------------------------------------------------------------------------\r
107# SSH agent\r
108# ---------------------------------------------------------------------------\r
109Write-Step 'Enabling ssh-agent'\r
110Set-Service -Name ssh-agent -StartupType Automatic\r
111if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }\r
112\r
113# ---------------------------------------------------------------------------\r
114# Visual Studio 2022 Community\r
115# ---------------------------------------------------------------------------\r
116$TempDir = Join-Path $env:TEMP 'dev_install'\r
117New-Item -ItemType Directory -Force -Path $TempDir | Out-Null\r
118\r
119# Component IDs split into independent groups so each can be installed in its\r
120# own pass. The base group is the known-good set; Clang and the Windows XP\r
121# toolset are layered on afterwards so a failure clearly identifies the culprit.\r
122# Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community\r
123$BaseComponents = @(\r
124 # Core C++ desktop workload\r
125 'Microsoft.VisualStudio.Workload.NativeDesktop'\r
126\r
127 # Spectre-mitigated MSVC runtime libs\r
128 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'\r
129 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'\r
130\r
131 # Spectre-mitigated ATL (needed for many driver/COM projects)\r
132 'Microsoft.VisualStudio.Component.VC.ATL.Spectre'\r
133\r
134 # Windows 11 SDK — build number must match the WDK below\r
135 'Microsoft.VisualStudio.Component.Windows11SDK.26100'\r
136\r
137 # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT\r
138 # install this (it only prompts interactively), so it must be added here.\r
139 'Component.Microsoft.Windows.DriverKit'\r
140)\r
141\r
142# Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang\r
143# compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.\r
144$ClangComponents = @(\r
145 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'\r
146 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'\r
147)\r
148\r
149# Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141\r
150# (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;\r
151# WinXP layers the XP-compatible CRT/SDK on top of it.\r
152$XpComponents = @(\r
153 'Microsoft.VisualStudio.Component.VC.v141.x86.x64'\r
154 'Microsoft.VisualStudio.Component.WinXP'\r
155)\r
156\r
157# Detect an existing VS install via vswhere (ships with the VS Installer).\r
158# These are referenced by Invoke-VsModify via $script: scope.\r
159$VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'\r
160$InstallPath = $null\r
161if (Test-Path $VsWhere) {\r
162 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
163 Select-Object -First 1\r
164}\r
165\r
166Write-Step 'Downloading VS2022 Community bootstrapper'\r
167$VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'\r
168$VsBootstrapper = Join-Path $TempDir 'vs_community.exe'\r
169Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing\r
170\r
171# Install in three sequential passes. The base set is installed first (this is\r
172# the configuration that previously worked); Clang and the XP toolset are added\r
173# afterwards. If one fails, its label pinpoints which group is responsible.\r
174Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents\r
175Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents\r
176Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents\r
177\r
178# ---------------------------------------------------------------------------\r
179# Verify the v141 / XP toolset actually landed. Earlier runs silently skipped\r
180# it and the failure only surfaced at build time, so check on disk and fail\r
181# loudly here instead.\r
182# ---------------------------------------------------------------------------\r
183Write-Step 'Verifying v141 / XP toolset'\r
184$InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
185 Select-Object -First 1\r
186$V141 = if ($InstallPath) {\r
187 Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |\r
188 Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1\r
189}\r
190if ($V141) {\r
191 Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green\r
192} else {\r
193 Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'\r
194 Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'\r
195 Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'\r
196 Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools'\r
197}\r
198\r
199# ---------------------------------------------------------------------------\r
200# Windows Driver Kit (WDK 10.0.26100)\r
201# Build 26100 matches the Windows 11 SDK installed above.\r
202# Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.\r
203# linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").\r
204# ---------------------------------------------------------------------------\r
205$WdkVersion = '10.0.26100'\r
206$WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `\r
207 -ErrorAction SilentlyContinue).WdkBinRootVersioned\r
208\r
209if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {\r
210 # Re-running wdksetup.exe for an already-present version returns exit code\r
211 # 2008 (maintenance mode / nothing to do), which is not a real failure.\r
212 Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"\r
213} else {\r
214 Write-Step 'Downloading WDK installer'\r
215 $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869'\r
216 $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'\r
217 Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing\r
218\r
219 Write-Step 'Installing WDK'\r
220 $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow\r
221 Write-Host " WDK installer exit code: $($proc.ExitCode)"\r
222 if ($proc.ExitCode -eq 2008) {\r
223 # 2008 = the WDK is already present; the installer has nothing to do.\r
224 Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow\r
225 } else {\r
226 Assert-ExitCode $proc.ExitCode 'WDK'\r
227 }\r
228}\r
229\r
230# ---------------------------------------------------------------------------\r
231# Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling,\r
232# used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature\r
233# that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it.\r
234# The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it\r
235# is the most reliable source. Idempotent (skips if xperf is already present in\r
236# either the SDK or ADK location) and non-fatal so it never aborts provisioning.\r
237# Lighter alternative if you don't want the full ADK: install the Windows SDK's\r
238# "Windows Performance Toolkit" optional feature via winsdksetup.exe /features\r
239# OptionId.WindowsPerformanceToolkit.\r
240# ---------------------------------------------------------------------------\r
241Write-Step 'Windows Performance Toolkit (xperf / WPA)'\r
242$wptRoots = @(\r
243 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
244 (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
245 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe')\r
246)\r
247$xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1\r
248if ($xperf) {\r
249 Write-Host " OK: WPT already present ($xperf)" -ForegroundColor Green\r
250} else {\r
251 try {\r
252 winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r
253 --accept-source-agreements --accept-package-agreements\r
254 Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.'\r
255 } catch {\r
256 Write-Warning "WPT install failed: $($_.Exception.Message)"\r
257 Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r
258 Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'\r
259 }\r
260}\r
261\r
262# ---------------------------------------------------------------------------\r
263Write-Host "`nAll done." -ForegroundColor Green\r
264Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r
265\r
266}\r
267catch {\r
268 $ExitCode = 1\r
269 Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red\r
270 if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }\r
271 # Only fold in the VS Installer logs when a VS step actually failed; for other\r
272 # steps (e.g. WDK) those logs are stale and misleading, so the message above\r
273 # is what matters.\r
274 if ($_.Exception.Message -match 'VS2022') {\r
275 try { Show-VsSetupLogs } catch {}\r
276 }\r
277}\r
278finally {\r
279 try { Stop-Transcript | Out-Null } catch {}\r
280\r
281 # This log was created by the elevated (admin) process, so by default the\r
282 # non-elevated caller can't delete it (their token has Administrators marked\r
283 # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs\r
284 # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known\r
285 # Users SID, used here so this is locale-independent.\r
286 try {\r
287 if (Test-Path $LogFile) {\r
288 $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')\r
289 $acl = Get-Acl -Path $LogFile\r
290 $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(\r
291 $usersSid, 'Modify', 'Allow')\r
292 $acl.AddAccessRule($rule)\r
293 Set-Acl -Path $LogFile -AclObject $acl\r
294 }\r
295 } catch {\r
296 Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow\r
297 }\r
298}\r
299\r
300exit $ExitCode\r