1 #Requires -RunAsAdministrator
\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
7 What this installs / configures:
\r
8 - ssh-agent set to automatic + started
\r
9 - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22
\r
10 - rsync for Windows (nuket/rsync-windows) in C:\Tools\rsync, on the machine PATH
\r
11 - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,
\r
12 Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)
\r
13 - Windows Driver Kit 10.0.26100
\r
15 Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:
\r
16 Professional : https://aka.ms/vs/17/release/vs_professional.exe
\r
17 Enterprise : https://aka.ms/vs/17/release/vs_enterprise.exe
\r
20 $ErrorActionPreference = 'Stop'
\r
22 function Write-Step([string]$Msg) {
\r
23 Write-Host "`n==> $Msg" -ForegroundColor Cyan
\r
26 function Assert-ExitCode([int]$Code, [string]$Step) {
\r
27 # 0 = success, 3010 = success + reboot required
\r
28 if ($Code -notin @(0, 3010)) {
\r
29 throw "$Step failed with exit code $Code"
\r
31 if ($Code -eq 3010) {
\r
32 Write-Host " [reboot required after $Step]" -ForegroundColor Yellow
\r
36 function Show-VsSetupLogs {
\r
37 # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because
\r
38 # this script runs elevated, that %TEMP% belongs to the elevated user and is
\r
39 # readable here even when it is NOT readable by the non-elevated caller. Fold
\r
40 # only the NEWEST installer + bootstrapper log into the transcript (the setup
\r
41 # engine log is where per-component / product errors actually appear) and
\r
42 # keep it short so the transcript stays readable.
\r
43 Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan
\r
44 $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |
\r
45 Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }
\r
47 $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
48 $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
49 $picks = $picks | Where-Object { $_ }
\r
51 Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow
\r
54 foreach ($l in $picks) {
\r
55 Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow
\r
56 Get-Content $l.FullName -Tail 40
\r
60 function Invoke-VsModify {
\r
61 # Run one VS install/modify pass for a named group of components. Splitting
\r
62 # the install into separate passes makes it obvious WHICH group fails: each
\r
63 # call prints its label and exit code before Assert-ExitCode throws.
\r
68 Write-Step "VS2022: $Label"
\r
69 $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '
\r
70 # --installPath must be quoted: it contains spaces ("C:\Program Files\...").
\r
71 # Windows PowerShell 5.1's Start-Process does not quote array elements, so we
\r
72 # hand-build a single string. Component IDs / flags have no spaces.
\r
73 $common = '--includeRecommended --quiet --norestart --wait'
\r
74 if ($script:InstallPath) {
\r
75 $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"
\r
77 # No existing install yet -> this first pass performs the base install.
\r
78 $argString = "$addStr $common"
\r
80 Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray
\r
81 $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow
\r
82 Write-Host " exit code: $($p.ExitCode)"
\r
83 Assert-ExitCode $p.ExitCode "VS2022 ($Label)"
\r
85 # After the first (fresh) install, re-detect the install path so subsequent
\r
86 # passes use `modify`.
\r
87 if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {
\r
88 $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |
\r
89 Select-Object -First 1
\r
93 # ---------------------------------------------------------------------------
\r
94 # This runs in a separate elevated window that closes the moment it exits, so
\r
95 # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror
\r
96 # all output to a log next to the script and exit with a real code so the
\r
97 # caller can detect success/failure and show the log.
\r
98 # ---------------------------------------------------------------------------
\r
99 $LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log'
\r
101 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}
\r
105 # ---------------------------------------------------------------------------
\r
106 # Base tools via winget
\r
107 # ---------------------------------------------------------------------------
\r
108 # ---------------------------------------------------------------------------
\r
110 # ---------------------------------------------------------------------------
\r
111 Write-Step 'Enabling ssh-agent'
\r
112 Set-Service -Name ssh-agent -StartupType Automatic
\r
113 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }
\r
115 # ---------------------------------------------------------------------------
\r
116 # OpenSSH Server (sshd)
\r
118 # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the
\r
119 # transport rsync rides on when seeding test data in. Ships with Windows 10
\r
120 # 1809+ / Windows 11 as an on-demand capability, so no third-party install.
\r
122 # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall
\r
123 # rule; we verify and create it if missing (it is absent on some images).
\r
125 # Non-fatal: a box that can't run sshd should still finish provisioning.
\r
126 # ---------------------------------------------------------------------------
\r
127 Write-Step 'OpenSSH Server (sshd)'
\r
129 $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |
\r
130 Select-Object -First 1
\r
132 Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'
\r
134 if ($sshd.State -ne 'Installed') {
\r
135 Write-Host " Installing $($sshd.Name) ..."
\r
136 $r = Add-WindowsCapability -Online -Name $sshd.Name
\r
137 if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Server]' -ForegroundColor Yellow }
\r
139 Write-Host " OK: $($sshd.Name) already installed"
\r
142 Set-Service -Name sshd -StartupType Automatic
\r
143 if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }
\r
144 Write-Host ' sshd: Automatic + running'
\r
146 # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and
\r
147 # bridged adapters are frequently classified Public, and the capability's
\r
148 # own rule is Private-only on some images, which is what leaves a plainly
\r
149 # running sshd plainly unreachable.
\r
151 # OpenSSH-Server-In-TCP is the name the capability itself uses, so this
\r
152 # WIDENS that rule rather than adding a second one next to it. Creating
\r
153 # our own under a different name would leave the narrow rule in place and
\r
154 # the box still unreachable on a Public-classified adapter; creating one
\r
155 # under the same name would collide. Adopt it if present, create it if not.
\r
156 $ruleName = 'OpenSSH-Server-In-TCP'
\r
157 if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {
\r
158 Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any
\r
159 Write-Host " Widened firewall rule $ruleName to all profiles"
\r
161 New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `
\r
162 -Enabled True -Direction Inbound -Protocol TCP -Action Allow `
\r
163 -LocalPort 22 -Profile Any | Out-Null
\r
164 Write-Host " Added firewall rule $ruleName (TCP 22, all profiles)"
\r
168 Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"
\r
171 # ---------------------------------------------------------------------------
\r
172 # rsync for Windows (github.com/nuket/rsync-windows)
\r
174 # Windows' OpenSSH ships the transport only - no rsync - so pushing test data
\r
175 # from a Linux box needs an rsync.exe on the Windows side.
\r
177 # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is
\r
178 # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes
\r
179 # the client-side --rsync-path escape hatch painful to quote. Added to the
\r
180 # MACHINE PATH so it resolves for every account, including the non-interactive
\r
181 # sshd session, which builds its environment from the machine + user registry
\r
182 # PATH rather than from a login shell.
\r
184 # Non-fatal: a download failure only warns.
\r
185 # ---------------------------------------------------------------------------
\r
186 Write-Step 'rsync for Windows'
\r
187 $RsyncUrl = 'https://github.com/nuket/rsync-windows/releases/download/v3.5.0-g521ad8ad/rsync.exe'
\r
188 $RsyncDir = 'C:\Tools\rsync'
\r
190 New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null
\r
191 $RsyncExe = Join-Path $RsyncDir 'rsync.exe'
\r
192 # Download to a temp name first so an interrupted transfer can't leave a
\r
193 # truncated rsync.exe sitting on the PATH.
\r
194 $tmpExe = "$RsyncExe.download"
\r
195 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
\r
196 Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpExe -UseBasicParsing
\r
197 Move-Item -Path $tmpExe -Destination $RsyncExe -Force
\r
198 Write-Host " Downloaded rsync.exe to $RsyncExe"
\r
200 # Machine PATH (HKLM environment). Idempotent: only appends if absent.
\r
201 $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')
\r
202 if (-not $m) { $m = '' }
\r
203 if (($m -split ';') -notcontains $RsyncDir) {
\r
204 $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }
\r
205 [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')
\r
206 Write-Host " Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."
\r
207 # sshd caches the environment it was started with, so an already-running
\r
208 # service would not see the new PATH until restarted.
\r
209 if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {
\r
210 Restart-Service sshd
\r
211 Write-Host ' Restarted sshd so it inherits the updated machine PATH.'
\r
214 Write-Host " OK: $RsyncDir already in the machine PATH"
\r
217 & $RsyncExe --version | Select-Object -First 1
\r
219 Write-Warning "rsync install failed: $($_.Exception.Message)"
\r
220 Write-Warning "Download manually from $RsyncUrl and drop it in $RsyncDir."
\r
223 # ---------------------------------------------------------------------------
\r
224 # Visual Studio 2022 Community
\r
225 # ---------------------------------------------------------------------------
\r
226 $TempDir = Join-Path $env:TEMP 'dev_install'
\r
227 New-Item -ItemType Directory -Force -Path $TempDir | Out-Null
\r
229 # Component IDs split into independent groups so each can be installed in its
\r
230 # own pass. The base group is the known-good set; Clang and the Windows XP
\r
231 # toolset are layered on afterwards so a failure clearly identifies the culprit.
\r
232 # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community
\r
233 $BaseComponents = @(
\r
234 # Core C++ desktop workload
\r
235 'Microsoft.VisualStudio.Workload.NativeDesktop'
\r
237 # Spectre-mitigated MSVC runtime libs
\r
238 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'
\r
239 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'
\r
241 # Spectre-mitigated ATL (needed for many driver/COM projects)
\r
242 'Microsoft.VisualStudio.Component.VC.ATL.Spectre'
\r
244 # Windows 11 SDK — build number must match the WDK below
\r
245 'Microsoft.VisualStudio.Component.Windows11SDK.26100'
\r
247 # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT
\r
248 # install this (it only prompts interactively), so it must be added here.
\r
249 'Component.Microsoft.Windows.DriverKit'
\r
252 # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang
\r
253 # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.
\r
254 $ClangComponents = @(
\r
255 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'
\r
256 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'
\r
259 # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141
\r
260 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;
\r
261 # WinXP layers the XP-compatible CRT/SDK on top of it.
\r
263 'Microsoft.VisualStudio.Component.VC.v141.x86.x64'
\r
264 'Microsoft.VisualStudio.Component.WinXP'
\r
267 # Detect an existing VS install via vswhere (ships with the VS Installer).
\r
268 # These are referenced by Invoke-VsModify via $script: scope.
\r
269 $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
\r
270 $InstallPath = $null
\r
271 if (Test-Path $VsWhere) {
\r
272 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
273 Select-Object -First 1
\r
276 Write-Step 'Downloading VS2022 Community bootstrapper'
\r
277 $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'
\r
278 $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'
\r
279 Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing
\r
281 # Install in three sequential passes. The base set is installed first (this is
\r
282 # the configuration that previously worked); Clang and the XP toolset are added
\r
283 # afterwards. If one fails, its label pinpoints which group is responsible.
\r
284 Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents
\r
285 Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents
\r
286 Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents
\r
288 # ---------------------------------------------------------------------------
\r
289 # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped
\r
290 # it and the failure only surfaced at build time, so check on disk and fail
\r
291 # loudly here instead.
\r
292 # ---------------------------------------------------------------------------
\r
293 Write-Step 'Verifying v141 / XP toolset'
\r
294 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
295 Select-Object -First 1
\r
296 $V141 = if ($InstallPath) {
\r
297 Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
\r
298 Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1
\r
301 Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green
\r
303 Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'
\r
304 Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'
\r
305 Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'
\r
306 Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools'
\r
309 # ---------------------------------------------------------------------------
\r
310 # Windows Driver Kit (WDK 10.0.26100)
\r
311 # Build 26100 matches the Windows 11 SDK installed above.
\r
312 # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.
\r
313 # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").
\r
314 # ---------------------------------------------------------------------------
\r
315 $WdkVersion = '10.0.26100'
\r
316 $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `
\r
317 -ErrorAction SilentlyContinue).WdkBinRootVersioned
\r
319 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {
\r
320 # Re-running wdksetup.exe for an already-present version returns exit code
\r
321 # 2008 (maintenance mode / nothing to do), which is not a real failure.
\r
322 Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"
\r
324 Write-Step 'Downloading WDK installer'
\r
325 $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869'
\r
326 $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'
\r
327 Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing
\r
329 Write-Step 'Installing WDK'
\r
330 $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow
\r
331 Write-Host " WDK installer exit code: $($proc.ExitCode)"
\r
332 if ($proc.ExitCode -eq 2008) {
\r
333 # 2008 = the WDK is already present; the installer has nothing to do.
\r
334 Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow
\r
336 Assert-ExitCode $proc.ExitCode 'WDK'
\r
340 # ---------------------------------------------------------------------------
\r
341 # Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling,
\r
342 # used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature
\r
343 # that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it.
\r
344 # The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it
\r
345 # is the most reliable source. Idempotent (skips if xperf is already present in
\r
346 # either the SDK or ADK location) and non-fatal so it never aborts provisioning.
\r
347 # Lighter alternative if you don't want the full ADK: install the Windows SDK's
\r
348 # "Windows Performance Toolkit" optional feature via winsdksetup.exe /features
\r
349 # OptionId.WindowsPerformanceToolkit.
\r
350 # ---------------------------------------------------------------------------
\r
351 Write-Step 'Windows Performance Toolkit (xperf / WPA)'
\r
353 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),
\r
354 (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),
\r
355 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe')
\r
357 $xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1
\r
359 Write-Host " OK: WPT already present ($xperf)" -ForegroundColor Green
\r
362 winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `
\r
363 --accept-source-agreements --accept-package-agreements
\r
364 Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.'
\r
366 Write-Warning "WPT install failed: $($_.Exception.Message)"
\r
367 Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'
\r
368 Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'
\r
372 # ---------------------------------------------------------------------------
\r
373 Write-Host "`nAll done." -ForegroundColor Green
\r
374 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'
\r
379 Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red
\r
380 if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }
\r
381 # Only fold in the VS Installer logs when a VS step actually failed; for other
\r
382 # steps (e.g. WDK) those logs are stale and misleading, so the message above
\r
384 if ($_.Exception.Message -match 'VS2022') {
\r
385 try { Show-VsSetupLogs } catch {}
\r
389 try { Stop-Transcript | Out-Null } catch {}
\r
391 # This log was created by the elevated (admin) process, so by default the
\r
392 # non-elevated caller can't delete it (their token has Administrators marked
\r
393 # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs
\r
394 # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known
\r
395 # Users SID, used here so this is locale-independent.
\r
397 if (Test-Path $LogFile) {
\r
398 $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')
\r
399 $acl = Get-Acl -Path $LogFile
\r
400 $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
\r
401 $usersSid, 'Modify', 'Allow')
\r
402 $acl.AddAccessRule($rule)
\r
403 Set-Acl -Path $LogFile -AclObject $acl
\r
406 Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow
\r