#Requires -RunAsAdministrator <# setup-windows-with-uac.ps1 Elevated portion of BlockBox Windows provisioning. Invoked by setup-windows.bat via Start-Process -Verb RunAs, or run manually from an Administrator prompt. What this installs / configures: - ssh-agent set to automatic + started - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX, Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset) - Windows Driver Kit 10.0.26100 Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed: Professional : https://aka.ms/vs/17/release/vs_professional.exe Enterprise : https://aka.ms/vs/17/release/vs_enterprise.exe #> $ErrorActionPreference = 'Stop' function Write-Step([string]$Msg) { Write-Host "`n==> $Msg" -ForegroundColor Cyan } function Assert-ExitCode([int]$Code, [string]$Step) { # 0 = success, 3010 = success + reboot required if ($Code -notin @(0, 3010)) { throw "$Step failed with exit code $Code" } if ($Code -eq 3010) { Write-Host " [reboot required after $Step]" -ForegroundColor Yellow } } function Show-VsSetupLogs { # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because # this script runs elevated, that %TEMP% belongs to the elevated user and is # readable here even when it is NOT readable by the non-elevated caller. Fold # only the NEWEST installer + bootstrapper log into the transcript (the setup # engine log is where per-component / product errors actually appear) and # keep it short so the transcript stays readable. Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) } $picks = @() $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1 $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1 $picks = $picks | Where-Object { $_ } if (-not $picks) { Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow return } foreach ($l in $picks) { Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow Get-Content $l.FullName -Tail 40 } } function Invoke-VsModify { # Run one VS install/modify pass for a named group of components. Splitting # the install into separate passes makes it obvious WHICH group fails: each # call prints its label and exit code before Assert-ExitCode throws. param( [string] $Label, [string[]] $Ids ) Write-Step "VS2022: $Label" $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' ' # --installPath must be quoted: it contains spaces ("C:\Program Files\..."). # Windows PowerShell 5.1's Start-Process does not quote array elements, so we # hand-build a single string. Component IDs / flags have no spaces. $common = '--includeRecommended --quiet --norestart --wait' if ($script:InstallPath) { $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force" } else { # No existing install yet -> this first pass performs the base install. $argString = "$addStr $common" } Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow Write-Host " exit code: $($p.ExitCode)" Assert-ExitCode $p.ExitCode "VS2022 ($Label)" # After the first (fresh) install, re-detect the install path so subsequent # passes use `modify`. if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) { $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value | Select-Object -First 1 } } # --------------------------------------------------------------------------- # This runs in a separate elevated window that closes the moment it exits, so # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror # all output to a log next to the script and exit with a real code so the # caller can detect success/failure and show the log. # --------------------------------------------------------------------------- $LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log' $ExitCode = 0 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {} try { # --------------------------------------------------------------------------- # Base tools via winget # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # SSH agent # --------------------------------------------------------------------------- Write-Step 'Enabling ssh-agent' Set-Service -Name ssh-agent -StartupType Automatic if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent } # --------------------------------------------------------------------------- # Visual Studio 2022 Community # --------------------------------------------------------------------------- $TempDir = Join-Path $env:TEMP 'dev_install' New-Item -ItemType Directory -Force -Path $TempDir | Out-Null # Component IDs split into independent groups so each can be installed in its # own pass. The base group is the known-good set; Clang and the Windows XP # toolset are layered on afterwards so a failure clearly identifies the culprit. # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community $BaseComponents = @( # Core C++ desktop workload 'Microsoft.VisualStudio.Workload.NativeDesktop' # Spectre-mitigated MSVC runtime libs 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre' 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre' # Spectre-mitigated ATL (needed for many driver/COM projects) 'Microsoft.VisualStudio.Component.VC.ATL.Spectre' # Windows 11 SDK — build number must match the WDK below 'Microsoft.VisualStudio.Component.Windows11SDK.26100' # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT # install this (it only prompts interactively), so it must be added here. 'Component.Microsoft.Windows.DriverKit' ) # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset. $ClangComponents = @( 'Microsoft.VisualStudio.Component.VC.Llvm.Clang' 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset' ) # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps; # WinXP layers the XP-compatible CRT/SDK on top of it. $XpComponents = @( 'Microsoft.VisualStudio.Component.VC.v141.x86.x64' 'Microsoft.VisualStudio.Component.WinXP' ) # Detect an existing VS install via vswhere (ships with the VS Installer). # These are referenced by Invoke-VsModify via $script: scope. $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' $InstallPath = $null if (Test-Path $VsWhere) { $InstallPath = & $VsWhere -products '*' -property installationPath -format value | Select-Object -First 1 } Write-Step 'Downloading VS2022 Community bootstrapper' $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe' $VsBootstrapper = Join-Path $TempDir 'vs_community.exe' Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing # Install in three sequential passes. The base set is installed first (this is # the configuration that previously worked); Clang and the XP toolset are added # afterwards. If one fails, its label pinpoints which group is responsible. Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents # --------------------------------------------------------------------------- # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped # it and the failure only surfaced at build time, so check on disk and fail # loudly here instead. # --------------------------------------------------------------------------- Write-Step 'Verifying v141 / XP toolset' $InstallPath = & $VsWhere -products '*' -property installationPath -format value | Select-Object -First 1 $V141 = if ($InstallPath) { Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1 } if ($V141) { Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green } else { Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.' Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:' Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)' Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools' } # --------------------------------------------------------------------------- # Windows Driver Kit (WDK 10.0.26100) # Build 26100 matches the Windows 11 SDK installed above. # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers. # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads"). # --------------------------------------------------------------------------- $WdkVersion = '10.0.26100' $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' ` -ErrorAction SilentlyContinue).WdkBinRootVersioned if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) { # Re-running wdksetup.exe for an already-present version returns exit code # 2008 (maintenance mode / nothing to do), which is not a real failure. Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)" } else { Write-Step 'Downloading WDK installer' $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869' $WdkInstaller = Join-Path $TempDir 'wdksetup.exe' Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing Write-Step 'Installing WDK' $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow Write-Host " WDK installer exit code: $($proc.ExitCode)" if ($proc.ExitCode -eq 2008) { # 2008 = the WDK is already present; the installer has nothing to do. Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow } else { Assert-ExitCode $proc.ExitCode 'WDK' } } # --------------------------------------------------------------------------- # Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling, # used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature # that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it. # The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it # is the most reliable source. Idempotent (skips if xperf is already present in # either the SDK or ADK location) and non-fatal so it never aborts provisioning. # Lighter alternative if you don't want the full ADK: install the Windows SDK's # "Windows Performance Toolkit" optional feature via winsdksetup.exe /features # OptionId.WindowsPerformanceToolkit. # --------------------------------------------------------------------------- Write-Step 'Windows Performance Toolkit (xperf / WPA)' $wptRoots = @( (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'), (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'), (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe') ) $xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1 if ($xperf) { Write-Host " OK: WPT already present ($xperf)" -ForegroundColor Green } else { try { winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity ` --accept-source-agreements --accept-package-agreements Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.' } catch { Write-Warning "WPT install failed: $($_.Exception.Message)" Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the' Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.' } } # --------------------------------------------------------------------------- Write-Host "`nAll done." -ForegroundColor Green Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.' } catch { $ExitCode = 1 Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray } # Only fold in the VS Installer logs when a VS step actually failed; for other # steps (e.g. WDK) those logs are stale and misleading, so the message above # is what matters. if ($_.Exception.Message -match 'VS2022') { try { Show-VsSetupLogs } catch {} } } finally { try { Stop-Transcript | Out-Null } catch {} # This log was created by the elevated (admin) process, so by default the # non-elevated caller can't delete it (their token has Administrators marked # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known # Users SID, used here so this is locale-independent. try { if (Test-Path $LogFile) { $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545') $acl = Get-Acl -Path $LogFile $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( $usersSid, 'Modify', 'Allow') $acl.AddAccessRule($rule) Set-Acl -Path $LogFile -AclObject $acl } } catch { Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow } } exit $ExitCode