]> vilimpoc.org git repositories - dotfiles/blob - setup-windows-with-uac.ps1
a546a0a7dc9d2cf44dccdea995f0665b6503903e
[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     - Windows Performance Toolkit - xperf, wpr and Windows Performance Analyzer\r
19       (wpa.exe) - on the machine PATH\r
20     - ETW collection rights for one ordinary account: Performance Log Users\r
21       membership plus the "Profile system performance" user right, so xperf and\r
22       wpr run WITHOUT elevation\r
23 \r
24   Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r
25     Professional : https://aka.ms/vs/17/release/vs_professional.exe\r
26     Enterprise   : https://aka.ms/vs/17/release/vs_enterprise.exe\r
27 #>\r
28 \r
29 param(\r
30     # Account to be granted non-elevated ETW collection rights (see the "ETW\r
31     # collection rights" step at the bottom). Defaults to the interactive\r
32     # console user, but setup-windows.bat passes it explicitly: with\r
33     # over-the-shoulder elevation THIS script runs as the administrator whose\r
34     # credentials went into the UAC prompt, not as the user who started the\r
35     # batch file, so $env:USERNAME here is the wrong answer.\r
36     #\r
37     # Pass an empty string to skip the group membership (the user right is still\r
38     # granted to the group, so adding an account later is one command).\r
39     [string] $TraceUser = '',\r
40 \r
41     # Do the ETW rights step and nothing else. That step is seconds of registry\r
42     # and LSA work with no downloads, where a full run is dominated by the three\r
43     # Visual Studio passes, which take minutes even when they have nothing to do.\r
44     # It is why the ETW step runs FIRST: -EtwRightsOnly is then just an early\r
45     # exit rather than a set of guards down the rest of the script.\r
46     [switch] $EtwRightsOnly\r
47 )\r
48 \r
49 $ErrorActionPreference = 'Stop'\r
50 \r
51 function Write-Step([string]$Msg) {\r
52     Write-Host "`n==> $Msg" -ForegroundColor Cyan\r
53 }\r
54 \r
55 function Assert-ExitCode([int]$Code, [string]$Step) {\r
56     # 0 = success, 3010 = success + reboot required\r
57     if ($Code -notin @(0, 3010)) {\r
58         throw "$Step failed with exit code $Code"\r
59     }\r
60     if ($Code -eq 3010) {\r
61         Write-Host "    [reboot required after $Step]" -ForegroundColor Yellow\r
62     }\r
63 }\r
64 \r
65 # ---------------------------------------------------------------------------\r
66 # User rights assignment (LSA account rights)\r
67 #\r
68 # Windows has no built-in cmdlet for "grant this SID this privilege". The two\r
69 # ways to script it are secedit (export the whole USER_RIGHTS area to an INF,\r
70 # edit one line, re-import) and the LSA API. The API is used here because it is\r
71 # surgical: LsaAddAccountRights adds exactly one right to exactly one SID and is\r
72 # a no-op when it is already held, where a secedit round-trip re-applies every\r
73 # user right on the box to fix one of them. The GUI equivalent, for a human, is\r
74 #     secpol.msc > Local Policies > User Rights Assignment\r
75 #\r
76 # The type is compiled on first use; C# 5 only, since Windows PowerShell 5.1's\r
77 # Add-Type compiles with the in-box CodeDom compiler.\r
78 # ---------------------------------------------------------------------------\r
79 function Initialize-LsaRightsType {\r
80     if ('LsaRights' -as [type]) { return }\r
81     Add-Type -TypeDefinition @'\r
82 using System;\r
83 using System.ComponentModel;\r
84 using System.Runtime.InteropServices;\r
85 \r
86 public static class LsaRights\r
87 {\r
88     [StructLayout(LayoutKind.Sequential)]\r
89     private struct LSA_UNICODE_STRING\r
90     {\r
91         public ushort Length;\r
92         public ushort MaximumLength;\r
93         public IntPtr Buffer;\r
94     }\r
95 \r
96     [StructLayout(LayoutKind.Sequential)]\r
97     private struct LSA_OBJECT_ATTRIBUTES\r
98     {\r
99         public int Length;\r
100         public IntPtr RootDirectory;\r
101         public IntPtr ObjectName;\r
102         public uint Attributes;\r
103         public IntPtr SecurityDescriptor;\r
104         public IntPtr SecurityQualityOfService;\r
105     }\r
106 \r
107     [DllImport("advapi32.dll", SetLastError = true)]\r
108     private static extern uint LsaOpenPolicy(IntPtr systemName,\r
109         ref LSA_OBJECT_ATTRIBUTES objectAttributes, uint desiredAccess, out IntPtr policyHandle);\r
110 \r
111     [DllImport("advapi32.dll", SetLastError = true)]\r
112     private static extern uint LsaAddAccountRights(IntPtr policyHandle, byte[] accountSid,\r
113         LSA_UNICODE_STRING[] userRights, uint countOfRights);\r
114 \r
115     [DllImport("advapi32.dll", SetLastError = true)]\r
116     private static extern uint LsaEnumerateAccountRights(IntPtr policyHandle, byte[] accountSid,\r
117         out IntPtr userRights, out uint countOfRights);\r
118 \r
119     [DllImport("advapi32.dll")]\r
120     private static extern uint LsaClose(IntPtr policyHandle);\r
121 \r
122     [DllImport("advapi32.dll")]\r
123     private static extern uint LsaFreeMemory(IntPtr buffer);\r
124 \r
125     [DllImport("advapi32.dll")]\r
126     private static extern int LsaNtStatusToWinError(uint status);\r
127 \r
128     private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001;\r
129     private const uint POLICY_CREATE_ACCOUNT         = 0x00000010;\r
130     private const uint POLICY_LOOKUP_NAMES           = 0x00000800;\r
131 \r
132     // Returned by LsaEnumerateAccountRights when the SID holds no rights at all,\r
133     // which is an empty list rather than an error.\r
134     private const uint STATUS_OBJECT_NAME_NOT_FOUND  = 0xC0000034;\r
135 \r
136     private static IntPtr OpenPolicy()\r
137     {\r
138         LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES();\r
139         attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));\r
140         IntPtr handle;\r
141         uint status = LsaOpenPolicy(IntPtr.Zero, ref attrs,\r
142             POLICY_VIEW_LOCAL_INFORMATION | POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, out handle);\r
143         if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
144         return handle;\r
145     }\r
146 \r
147     public static string[] Get(byte[] sid)\r
148     {\r
149         IntPtr policy = OpenPolicy();\r
150         try\r
151         {\r
152             IntPtr rights;\r
153             uint count;\r
154             uint status = LsaEnumerateAccountRights(policy, sid, out rights, out count);\r
155             if (status == STATUS_OBJECT_NAME_NOT_FOUND) { return new string[0]; }\r
156             if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
157             try\r
158             {\r
159                 string[] result = new string[count];\r
160                 int stride = Marshal.SizeOf(typeof(LSA_UNICODE_STRING));\r
161                 for (int i = 0; i < count; i++)\r
162                 {\r
163                     LSA_UNICODE_STRING s = (LSA_UNICODE_STRING)Marshal.PtrToStructure(\r
164                         new IntPtr(rights.ToInt64() + (long)i * stride), typeof(LSA_UNICODE_STRING));\r
165                     result[i] = Marshal.PtrToStringUni(s.Buffer, s.Length / 2);\r
166                 }\r
167                 return result;\r
168             }\r
169             finally { LsaFreeMemory(rights); }\r
170         }\r
171         finally { LsaClose(policy); }\r
172     }\r
173 \r
174     public static void Add(byte[] sid, string right)\r
175     {\r
176         IntPtr policy = OpenPolicy();\r
177         try\r
178         {\r
179             LSA_UNICODE_STRING[] rights = new LSA_UNICODE_STRING[1];\r
180             rights[0].Buffer = Marshal.StringToHGlobalUni(right);\r
181             // Length counts BYTES and excludes the terminator; MaximumLength includes it.\r
182             rights[0].Length = (ushort)(right.Length * 2);\r
183             rights[0].MaximumLength = (ushort)(right.Length * 2 + 2);\r
184             try\r
185             {\r
186                 uint status = LsaAddAccountRights(policy, sid, rights, 1);\r
187                 if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
188             }\r
189             finally { Marshal.FreeHGlobal(rights[0].Buffer); }\r
190         }\r
191         finally { LsaClose(policy); }\r
192     }\r
193 }\r
194 '@\r
195 }\r
196 \r
197 function Get-SidBytes([string]$Sid) {\r
198     $s = New-Object System.Security.Principal.SecurityIdentifier($Sid)\r
199     $bytes = New-Object byte[] $s.BinaryLength\r
200     $s.GetBinaryForm($bytes, 0)\r
201     return ,$bytes\r
202 }\r
203 \r
204 function Get-AccountRight([string]$Sid) {\r
205     Initialize-LsaRightsType\r
206     return [LsaRights]::Get((Get-SidBytes $Sid))\r
207 }\r
208 \r
209 function Grant-AccountRight([string]$Sid, [string]$Right) {\r
210     Initialize-LsaRightsType\r
211     [LsaRights]::Add((Get-SidBytes $Sid), $Right)\r
212 }\r
213 \r
214 # ---------------------------------------------------------------------------\r
215 # ETW provider-GUID access control\r
216 #\r
217 # ETW keeps a security descriptor per provider GUID under\r
218 # HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security, and EventAccessControl is\r
219 # the documented way to edit one. Editing the registry value directly would work\r
220 # too - it is a self-relative SD in a REG_BINARY - but the API takes the SID and\r
221 # the rights mask and leaves the descriptor's shape to Windows.\r
222 # ---------------------------------------------------------------------------\r
223 function Initialize-EtwAclType {\r
224     if ('EtwAcl' -as [type]) { return }\r
225     Add-Type -TypeDefinition @'\r
226 using System;\r
227 using System.Runtime.InteropServices;\r
228 \r
229 public static class EtwAcl\r
230 {\r
231     // ULONG EventAccessControl(LPGUID, ULONG Operation, PSID, ULONG Rights, BOOLEAN AllowOrDeny)\r
232     [DllImport("advapi32.dll", SetLastError = true)]\r
233     public static extern uint EventAccessControl(ref Guid guid, uint operation, byte[] sid,\r
234         uint rights, [MarshalAs(UnmanagedType.U1)] bool allowOrDeny);\r
235 \r
236     // ULONG EventAccessQuery(LPGUID, PSECURITY_DESCRIPTOR, PULONG BufferSize)\r
237     [DllImport("advapi32.dll", SetLastError = true)]\r
238     public static extern uint EventAccessQuery(ref Guid guid, byte[] buffer, ref uint bufferSize);\r
239 }\r
240 '@\r
241 }\r
242 \r
243 # The rights a session controller needs, from evntrace.h:\r
244 #   0x0001 WMIGUID_QUERY               0x0100 TRACELOG_ACCESS_KERNEL_LOGGER\r
245 #   0x0020 TRACELOG_CREATE_REALTIME    0x0200 TRACELOG_LOG_EVENT\r
246 #   0x0040 TRACELOG_CREATE_ONDISK      0x0400 TRACELOG_ACCESS_REALTIME\r
247 #   0x0080 TRACELOG_GUID_ENABLE        0x0800 TRACELOG_REGISTER_GUIDS\r
248 # TRACELOG_ACCESS_KERNEL_LOGGER is the one that names the NT Kernel Logger\r
249 # specifically; the rest are what any controller needs to create a session,\r
250 # write it to disk and enable providers on it.\r
251 $EtwControllerRights = 0x0FE1\r
252 \r
253 function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) {\r
254     Initialize-EtwAclType\r
255     $g = [Guid]$Guid\r
256     # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing\r
257     # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which\r
258     # on the kernel logger means removing the entries Windows itself relies on.\r
259     $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true)\r
260     if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) }\r
261 }\r
262 \r
263 function Get-EtwGuidSddl([string]$Guid) {\r
264     Initialize-EtwAclType\r
265     $g = [Guid]$Guid\r
266     $size = [uint32]0\r
267     [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size)\r
268     if ($size -eq 0) { return $null }\r
269     $buf = New-Object byte[] $size\r
270     if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null }\r
271     return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access')\r
272 }\r
273 \r
274 function Show-VsSetupLogs {\r
275     # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because\r
276     # this script runs elevated, that %TEMP% belongs to the elevated user and is\r
277     # readable here even when it is NOT readable by the non-elevated caller. Fold\r
278     # only the NEWEST installer + bootstrapper log into the transcript (the setup\r
279     # engine log is where per-component / product errors actually appear) and\r
280     # keep it short so the transcript stays readable.\r
281     Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan\r
282     $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |\r
283               Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }\r
284     $picks = @()\r
285     $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*'    } | Sort-Object LastWriteTime | Select-Object -Last 1\r
286     $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r
287     $picks = $picks | Where-Object { $_ }\r
288     if (-not $picks) {\r
289         Write-Host '    (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow\r
290         return\r
291     }\r
292     foreach ($l in $picks) {\r
293         Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow\r
294         Get-Content $l.FullName -Tail 40\r
295     }\r
296 }\r
297 \r
298 function Invoke-VsModify {\r
299     # Run one VS install/modify pass for a named group of components. Splitting\r
300     # the install into separate passes makes it obvious WHICH group fails: each\r
301     # call prints its label and exit code before Assert-ExitCode throws.\r
302     param(\r
303         [string]   $Label,\r
304         [string[]] $Ids\r
305     )\r
306     Write-Step "VS2022: $Label"\r
307     $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '\r
308     # --installPath must be quoted: it contains spaces ("C:\Program Files\...").\r
309     # Windows PowerShell 5.1's Start-Process does not quote array elements, so we\r
310     # hand-build a single string. Component IDs / flags have no spaces.\r
311     $common = '--includeRecommended --quiet --norestart --wait'\r
312     if ($script:InstallPath) {\r
313         $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"\r
314     } else {\r
315         # No existing install yet -> this first pass performs the base install.\r
316         $argString = "$addStr $common"\r
317     }\r
318     Write-Host "    > $script:VsBootstrapper $argString" -ForegroundColor DarkGray\r
319     $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow\r
320     Write-Host "    exit code: $($p.ExitCode)"\r
321     Assert-ExitCode $p.ExitCode "VS2022 ($Label)"\r
322 \r
323     # After the first (fresh) install, re-detect the install path so subsequent\r
324     # passes use `modify`.\r
325     if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {\r
326         $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |\r
327                               Select-Object -First 1\r
328     }\r
329 }\r
330 \r
331 # ---------------------------------------------------------------------------\r
332 # This runs in a separate elevated window that closes the moment it exits, so\r
333 # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror\r
334 # all output to a log next to the script and exit with a real code so the\r
335 # caller can detect success/failure and show the log.\r
336 # ---------------------------------------------------------------------------\r
337 $LogFile  = Join-Path $PSScriptRoot 'setup-windows-uac.log'\r
338 $ExitCode = 0\r
339 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}\r
340 \r
341 try {\r
342 \r
343 # ---------------------------------------------------------------------------\r
344 # ETW collection rights for an ordinary account\r
345 #\r
346 # Out of the box, xperf and wpr only work elevated. THREE separate things stand\r
347 # in a standard user's way, and each has its own error:\r
348 #\r
349 #     xperf -on base         -> "NT Kernel Logger: Access is denied. (0x5)"\r
350 #     wpr -start GeneralProfile\r
351 #                            -> "Failed to enable the policy to profile system\r
352 #                                performance."  (0xc5585011)\r
353 #\r
354 # 1. Creating or controlling ANY event tracing session - even a user-mode one\r
355 #    naming a single provider - is checked against the security descriptor ETW\r
356 #    keeps per provider GUID under\r
357 #    HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor\r
358 #    grants the session-control rights (TRACELOG_CREATE_ONDISK,\r
359 #    TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to\r
360 #    SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log\r
361 #    Users - and to nobody else. That group is the supported hook; its own\r
362 #    description says members "may ... enable trace providers, and collect event\r
363 #    traces".\r
364 #\r
365 # 2. Switching on the kernel/system trace provider on top of that needs the\r
366 #    SeSystemProfilePrivilege user right ("Profile system performance"), held by\r
367 #    default only by Administrators and NT SERVICE\WdiServiceHost. That is the\r
368 #    one wpr names in its error.\r
369 #\r
370 # 3. The kernel logger is not covered by that default descriptor. Its own GUID -\r
371 #    SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries\r
372 #    an explicit descriptor that does not mention Performance Log Users, so 1 and\r
373 #    2 are not enough by themselves. Measured on this box with both in place: a\r
374 #    user-mode session starts (exit 0) and the account holds the privilege, and\r
375 #    `xperf -on base` still answers "NT Kernel Logger: Access is denied" while\r
376 #    wpr's error changes from the policy message above to a bare 0x80070005.\r
377 #    Even READING that descriptor comes back access-denied, which is the tell. So\r
378 #    add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER\r
379 #    is the right that names this particular session.\r
380 #\r
381 # The privilege and the ACE both go to the GROUP, and the account then goes into\r
382 # the group: membership alone becomes the switch, and enabling the next account\r
383 # is one `net localgroup` away with no policy or registry edit.\r
384 #\r
385 # What this costs, stated plainly: a member of that group can capture\r
386 # system-wide kernel traces - process, image, file and registry activity across\r
387 # every account on the box, paths and command lines included. That is what the\r
388 # group is for, and it is the price of collecting a trace without a UAC prompt.\r
389 #\r
390 # Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU\r
391 # sampling nor walking stacks in your own processes, and it is equivalent to\r
392 # handing out administrator.\r
393 #\r
394 # THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership\r
395 # are baked into the access token at LOGON, and UAC hands an administrator a\r
396 # filtered token that keeps just five harmless privileges - so an admin's\r
397 # ordinary shell still cannot trace, however the policy reads. Running as a\r
398 # standard user is what makes this work.\r
399 #\r
400 # For the same reason 1 and 2 do not take effect in an already-open session: the\r
401 # account has to sign out and back in. Any NEW logon does it - an ssh login into\r
402 # this box is one, which is the quick way to check without dropping the desktop.\r
403 # The ACE in 3 is machine state, read when a session is started, so that one\r
404 # applies immediately.\r
405 #\r
406 # Analysis never needed any of this: wpa.exe opens an existing .etl as a plain\r
407 # user. This step is only about collection.\r
408 # ---------------------------------------------------------------------------\r
409 Write-Step 'ETW collection rights (non-elevated xperf / wpr)'\r
410 $PerfLogUsersSid = 'S-1-5-32-559'   # BUILTIN\Performance Log Users\r
411 # SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on\r
412 # and wpr both drive. Fixed by contract, from evntrace.h.\r
413 $SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939'\r
414 try {\r
415     # --- The user right, granted to the group ---\r
416     $existing = Get-AccountRight $PerfLogUsersSid\r
417     if ($existing -contains 'SeSystemProfilePrivilege') {\r
418         Write-Host '    OK: Performance Log Users already holds SeSystemProfilePrivilege'\r
419     } else {\r
420         Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'\r
421         Write-Host '    Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'\r
422     }\r
423 \r
424     # --- The kernel logger's own descriptor ---\r
425     # Idempotent: adding the ACE for a SID that already has it rewrites the same\r
426     # entry. Kept in its own try so that a failure here still leaves the group\r
427     # membership below to be done - user-mode sessions work without it.\r
428     try {\r
429         Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights\r
430         Write-Host ("    Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights)\r
431         $sddl = Get-EtwGuidSddl $SystemTraceControlGuid\r
432         if ($sddl) { Write-Host "    kernel logger DACL is now $sddl" -ForegroundColor DarkGray }\r
433     } catch {\r
434         Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)"\r
435         Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."'\r
436     }\r
437 \r
438     # --- The membership ---\r
439     # Fall back to the console user when the caller did not name one: with\r
440     # over-the-shoulder elevation that is the person who started\r
441     # setup-windows.bat, which is who wants to trace.\r
442     $target = $TraceUser\r
443     if (-not $target) {\r
444         $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName\r
445         if ($target) { Write-Host "    No -TraceUser given; using the console user $target" }\r
446     }\r
447 \r
448     if (-not $target) {\r
449         Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'\r
450         Write-Warning 'The user right is in place, so this is the only step left:'\r
451         Write-Warning '    net localgroup "Performance Log Users" DOMAIN\user /add'\r
452     } else {\r
453         # Resolve to a SID first: it validates the name, and it is what the\r
454         # membership check compares, so a member spelled ".\claude" in one place\r
455         # and "LATISLAB\claude" in another is still recognised as the same account.\r
456         $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(\r
457                         [System.Security.Principal.SecurityIdentifier])\r
458 \r
459         # By SID, never by name: "Performance Log Users" is localised, and\r
460         # Get-LocalGroup -SID is how this stays correct on a non-English box.\r
461         $group = Get-LocalGroup -SID $PerfLogUsersSid\r
462 \r
463         # Get-LocalGroupMember throws on a group holding a SID that no longer\r
464         # resolves (a known Windows 10 bug), so a failure to READ the membership\r
465         # must not stop us from writing it - fall through and let the add report.\r
466         $already = $false\r
467         try {\r
468             $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |\r
469                          Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0\r
470         } catch {\r
471             Write-Host "    (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray\r
472         }\r
473 \r
474         if ($already) {\r
475             Write-Host "    OK: $target is already in $($group.Name)"\r
476         } else {\r
477             try {\r
478                 Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value\r
479             } catch {\r
480                 # "already a member" is only reachable when the enumeration above\r
481                 # failed, and is not an error. Matched on the type NAME rather\r
482                 # than in a typed catch clause: catch types are resolved when the\r
483                 # script is PARSED, before the LocalAccounts module has been\r
484                 # autoloaded, so naming the type there is a parse error that\r
485                 # would take the whole script down.\r
486                 if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }\r
487             }\r
488             Write-Host "    Added $target to $($group.Name)"\r
489         }\r
490 \r
491         Write-Host ''\r
492         Write-Host "    $target must sign out and back in before this takes effect." -ForegroundColor Yellow\r
493         Write-Host '    Then, from that account (NOT elevated):' -ForegroundColor Yellow\r
494         Write-Host '        whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow\r
495         Write-Host '        xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow\r
496     }\r
497 } catch {\r
498     Write-Warning "ETW rights setup failed: $($_.Exception.Message)"\r
499     Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'\r
500     Write-Warning '"Profile system performance" > add Performance Log Users, then'\r
501     Write-Warning '    net localgroup "Performance Log Users" <user> /add'\r
502 }\r
503 \r
504 if ($EtwRightsOnly) {\r
505     # `exit` inside the try still runs the finally below, so the transcript is\r
506     # stopped and the log is left readable by the non-elevated caller.\r
507     Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green\r
508     exit 0\r
509 }\r
510 \r
511 \r
512 # ---------------------------------------------------------------------------\r
513 # Base tools via winget\r
514 # ---------------------------------------------------------------------------\r
515 \r
516 # ---------------------------------------------------------------------------\r
517 # OpenSSH Client\r
518 #\r
519 # Present by default on Windows 10 1809+ / Windows 11, but removable, and absent\r
520 # from some Server images. Two things below want it: rsync does not speak ssh\r
521 # itself, it execs an ssh binary, and the release's own ssh.exe links against the\r
522 # libcrypto.dll this capability puts in System32. It also owns the ssh-agent\r
523 # service configured next, so a missing client is why that step would fail.\r
524 #\r
525 # Non-fatal, like the server half below: a box that cannot have it should still\r
526 # finish provisioning.\r
527 # ---------------------------------------------------------------------------\r
528 Write-Step 'OpenSSH Client'\r
529 try {\r
530     $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |\r
531             Select-Object -First 1\r
532     if (-not $sshc) {\r
533         Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'\r
534     } elseif ($sshc.State -eq 'Installed') {\r
535         Write-Host "    OK: $($sshc.Name) already installed"\r
536     } else {\r
537         Write-Host "    Installing $($sshc.Name) ..."\r
538         $r = Add-WindowsCapability -Online -Name $sshc.Name\r
539         if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Client]' -ForegroundColor Yellow }\r
540     }\r
541 } catch {\r
542     Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"\r
543 }\r
544 \r
545 # ---------------------------------------------------------------------------\r
546 # SSH agent\r
547 # ---------------------------------------------------------------------------\r
548 Write-Step 'Enabling ssh-agent'\r
549 Set-Service -Name ssh-agent -StartupType Automatic\r
550 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }\r
551 \r
552 # ---------------------------------------------------------------------------\r
553 # OpenSSH Server (sshd)\r
554 #\r
555 # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the\r
556 # transport rsync rides on when seeding test data in. Ships with Windows 10\r
557 # 1809+ / Windows 11 as an on-demand capability, so no third-party install.\r
558 #\r
559 # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall\r
560 # rule; we verify and create it if missing (it is absent on some images).\r
561 #\r
562 # Non-fatal: a box that can't run sshd should still finish provisioning.\r
563 # ---------------------------------------------------------------------------\r
564 Write-Step 'OpenSSH Server (sshd)'\r
565 try {\r
566     $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |\r
567             Select-Object -First 1\r
568     if (-not $sshd) {\r
569         Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'\r
570     } else {\r
571         if ($sshd.State -ne 'Installed') {\r
572             Write-Host "    Installing $($sshd.Name) ..."\r
573             $r = Add-WindowsCapability -Online -Name $sshd.Name\r
574             if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Server]' -ForegroundColor Yellow }\r
575         } else {\r
576             Write-Host "    OK: $($sshd.Name) already installed"\r
577         }\r
578 \r
579         Set-Service -Name sshd -StartupType Automatic\r
580         if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }\r
581         Write-Host '    sshd: Automatic + running'\r
582 \r
583         # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and\r
584         # bridged adapters are frequently classified Public, and the capability's\r
585         # own rule is Private-only on some images, which is what leaves a plainly\r
586         # running sshd plainly unreachable.\r
587         #\r
588         # OpenSSH-Server-In-TCP is the name the capability itself uses, so this\r
589         # WIDENS that rule rather than adding a second one next to it. Creating\r
590         # our own under a different name would leave the narrow rule in place and\r
591         # the box still unreachable on a Public-classified adapter; creating one\r
592         # under the same name would collide. Adopt it if present, create it if not.\r
593         $ruleName = 'OpenSSH-Server-In-TCP'\r
594         if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {\r
595             Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any\r
596             Write-Host "    Widened firewall rule $ruleName to all profiles"\r
597         } else {\r
598             New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `\r
599                 -Enabled True -Direction Inbound -Protocol TCP -Action Allow `\r
600                 -LocalPort 22 -Profile Any | Out-Null\r
601             Write-Host "    Added firewall rule $ruleName (TCP 22, all profiles)"\r
602         }\r
603     }\r
604 } catch {\r
605     Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"\r
606 }\r
607 \r
608 # ---------------------------------------------------------------------------\r
609 # rsync for Windows (github.com/nuket/rsync-windows)\r
610 #\r
611 # Windows' OpenSSH ships the transport only - no rsync - so pushing test data\r
612 # from a Linux box needs an rsync.exe on the Windows side.\r
613 #\r
614 # The release is one zip per architecture - rsync-windows-x64.zip and\r
615 # rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the\r
616 # licence texts under exactly those names. Both exes are installed, together:\r
617 # rsync.exe prefers an ssh.exe in its own directory, and the release's build is\r
618 # what makes a push FROM this box run at line rate. The ssh.exe Windows ships\r
619 # reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the\r
620 # link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same\r
621 # known_hosts - and a bare `ssh` still resolves to the in-box client, which sits\r
622 # ahead of C:\Tools\rsync on the machine PATH.\r
623 #\r
624 # That ssh.exe links against the libcrypto.dll the OpenSSH Client capability\r
625 # above puts in System32: Windows' own LibreSSL, and the fast one, since it uses\r
626 # AES-NI. No copy of it ships in the zip, so where the capability is missing we\r
627 # unpack rsync alone rather than an ssh.exe that will not start.\r
628 #\r
629 # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is\r
630 # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes\r
631 # the client-side --rsync-path escape hatch painful to quote. Added to the\r
632 # MACHINE PATH so it resolves for every account, including the non-interactive\r
633 # sshd session, which builds its environment from the machine + user registry\r
634 # PATH rather than from a login shell.\r
635 #\r
636 # Non-fatal: a download failure only warns.\r
637 # ---------------------------------------------------------------------------\r
638 Write-Step 'rsync for Windows'\r
639 $RsyncRepo  = 'nuket/rsync-windows'\r
640 $RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }\r
641 # The /releases/latest/download/ redirect rather than the API: unauthenticated\r
642 # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a\r
643 # shared NAT can genuinely exhaust, and the redirect costs none of that budget.\r
644 # To hold a box on a known build, pin the tag instead:\r
645 #     .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset\r
646 $RsyncUrl   = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"\r
647 $RsyncDir   = 'C:\Tools\rsync'\r
648 try {\r
649     New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null\r
650     $RsyncExe = Join-Path $RsyncDir 'rsync.exe'\r
651 \r
652     # Does the release's ssh.exe have the libcrypto it needs? Decided before the\r
653     # download so the answer can also gate what comes out of the zip.\r
654     $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'\r
655     $WantSsh   = Test-Path $SysCrypto\r
656     if (-not $WantSsh) {\r
657         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
658     } else {\r
659         $v = (Get-Item $SysCrypto).VersionInfo.FileVersion\r
660         if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {\r
661             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
662         }\r
663     }\r
664 \r
665     # Download and unpack beside the targets, not over them, so an interrupted\r
666     # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch\r
667     # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive\r
668     # refuses any other extension outright ("*.download is not a supported\r
669     # archive file format"), where PowerShell 7 just reads the file.\r
670     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\r
671     $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"\r
672     Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing\r
673     Write-Host "    Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"\r
674 \r
675     # Verify against the .sha256 published beside it. Same origin, so this is an\r
676     # integrity check on the transfer rather than a defence against a hostile\r
677     # release - but a truncated or proxy-mangled download is the failure that\r
678     # actually happens, and it fails here instead of mid-transfer later.\r
679     #\r
680     # -OutFile, not .Content: GitHub serves the .sha256 as\r
681     # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather\r
682     # than a string for any non-text content type, so .Content would compare the\r
683     # first BYTE against the hash and fail on every correct download.\r
684     $tmpSha = "$tmpZip.sha256"\r
685     Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing\r
686     $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()\r
687     Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue\r
688     $got  = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()\r
689     if ($want -and $want -ne $got) {\r
690         Remove-Item $tmpZip -Force\r
691         throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"\r
692     }\r
693     Write-Host "    SHA-256 verified: $got"\r
694 \r
695     # Unpack to a scratch directory and move out the files we asked for, rather\r
696     # than expanding straight over the install directory: the zip is the unit\r
697     # that was checksummed, and this way a future release adding something to it\r
698     # cannot quietly drop that something onto the machine PATH.\r
699     $unpack = Join-Path $RsyncDir '.unpack'\r
700     if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }\r
701     Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force\r
702     Remove-Item $tmpZip -Force\r
703     foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {\r
704         $src = Join-Path $unpack $f\r
705         if (-not (Test-Path $src)) { continue }\r
706         if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }\r
707         Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force\r
708     }\r
709     Remove-Item -Recurse -Force $unpack\r
710     Write-Host "    Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"\r
711 \r
712     # Machine PATH (HKLM environment). Idempotent: only appends if absent.\r
713     $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
714     if (-not $m) { $m = '' }\r
715     if (($m -split ';') -notcontains $RsyncDir) {\r
716         $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }\r
717         [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
718         Write-Host "    Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."\r
719         # sshd caches the environment it was started with, so an already-running\r
720         # service would not see the new PATH until restarted.\r
721         if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {\r
722             Restart-Service sshd\r
723             Write-Host '    Restarted sshd so it inherits the updated machine PATH.'\r
724         }\r
725     } else {\r
726         Write-Host "    OK: $RsyncDir already in the machine PATH"\r
727     }\r
728 \r
729     & $RsyncExe --version | Select-Object -First 1\r
730 } catch {\r
731     Write-Warning "rsync install failed: $($_.Exception.Message)"\r
732     Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"\r
733     Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."\r
734 }\r
735 \r
736 # ---------------------------------------------------------------------------\r
737 # Visual Studio 2022 Community\r
738 # ---------------------------------------------------------------------------\r
739 $TempDir = Join-Path $env:TEMP 'dev_install'\r
740 New-Item -ItemType Directory -Force -Path $TempDir | Out-Null\r
741 \r
742 # Component IDs split into independent groups so each can be installed in its\r
743 # own pass. The base group is the known-good set; Clang and the Windows XP\r
744 # toolset are layered on afterwards so a failure clearly identifies the culprit.\r
745 # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community\r
746 $BaseComponents = @(\r
747     # Core C++ desktop workload\r
748     'Microsoft.VisualStudio.Workload.NativeDesktop'\r
749 \r
750     # Spectre-mitigated MSVC runtime libs\r
751     'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'\r
752     'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'\r
753 \r
754     # Spectre-mitigated ATL (needed for many driver/COM projects)\r
755     'Microsoft.VisualStudio.Component.VC.ATL.Spectre'\r
756 \r
757     # Windows 11 SDK — build number must match the WDK below\r
758     'Microsoft.VisualStudio.Component.Windows11SDK.26100'\r
759 \r
760     # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT\r
761     # install this (it only prompts interactively), so it must be added here.\r
762     'Component.Microsoft.Windows.DriverKit'\r
763 )\r
764 \r
765 # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang\r
766 # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.\r
767 $ClangComponents = @(\r
768     'Microsoft.VisualStudio.Component.VC.Llvm.Clang'\r
769     'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'\r
770 )\r
771 \r
772 # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141\r
773 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;\r
774 # WinXP layers the XP-compatible CRT/SDK on top of it.\r
775 $XpComponents = @(\r
776     'Microsoft.VisualStudio.Component.VC.v141.x86.x64'\r
777     'Microsoft.VisualStudio.Component.WinXP'\r
778 )\r
779 \r
780 # Detect an existing VS install via vswhere (ships with the VS Installer).\r
781 # These are referenced by Invoke-VsModify via $script: scope.\r
782 $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'\r
783 $InstallPath = $null\r
784 if (Test-Path $VsWhere) {\r
785     $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
786                    Select-Object -First 1\r
787 }\r
788 \r
789 Write-Step 'Downloading VS2022 Community bootstrapper'\r
790 $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'\r
791 $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'\r
792 Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing\r
793 \r
794 # Install in three sequential passes. The base set is installed first (this is\r
795 # the configuration that previously worked); Clang and the XP toolset are added\r
796 # afterwards. If one fails, its label pinpoints which group is responsible.\r
797 Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents\r
798 Invoke-VsModify -Label 'Clang / LLVM'            -Ids $ClangComponents\r
799 Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents\r
800 \r
801 # ---------------------------------------------------------------------------\r
802 # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped\r
803 # it and the failure only surfaced at build time, so check on disk and fail\r
804 # loudly here instead.\r
805 # ---------------------------------------------------------------------------\r
806 Write-Step 'Verifying v141 / XP toolset'\r
807 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r
808                Select-Object -First 1\r
809 $V141 = if ($InstallPath) {\r
810     Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |\r
811         Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1\r
812 }\r
813 if ($V141) {\r
814     Write-Host "    OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green\r
815 } else {\r
816     Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'\r
817     Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'\r
818     Write-Warning '  - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'\r
819     Write-Warning '  - C++ Windows XP Support for VS 2017 (v141) tools'\r
820 }\r
821 \r
822 # ---------------------------------------------------------------------------\r
823 # Windows Driver Kit (WDK 10.0.26100)\r
824 # Build 26100 matches the Windows 11 SDK installed above.\r
825 # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.\r
826 # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").\r
827 # ---------------------------------------------------------------------------\r
828 $WdkVersion = '10.0.26100'\r
829 $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `\r
830                         -ErrorAction SilentlyContinue).WdkBinRootVersioned\r
831 \r
832 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {\r
833     # Re-running wdksetup.exe for an already-present version returns exit code\r
834     # 2008 (maintenance mode / nothing to do), which is not a real failure.\r
835     Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"\r
836 } else {\r
837     Write-Step 'Downloading WDK installer'\r
838     $WdkUrl       = 'https://go.microsoft.com/fwlink/?linkid=2335869'\r
839     $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'\r
840     Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing\r
841 \r
842     Write-Step 'Installing WDK'\r
843     $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow\r
844     Write-Host "    WDK installer exit code: $($proc.ExitCode)"\r
845     if ($proc.ExitCode -eq 2008) {\r
846         # 2008 = the WDK is already present; the installer has nothing to do.\r
847         Write-Host '    [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow\r
848     } else {\r
849         Assert-ExitCode $proc.ExitCode 'WDK'\r
850     }\r
851 }\r
852 \r
853 # ---------------------------------------------------------------------------\r
854 # Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer\r
855 # (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.\r
856 #\r
857 # WPA is NOT a Visual Studio component and has no relationship to VS's own\r
858 # Performance Profiler (a separate, .diagsession-based tool that cannot open an\r
859 # .etl). It ships in exactly two places: as an optional FEATURE of the Windows\r
860 # SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and\r
861 # in the Windows ADK, which bundles the same toolkit. Whether the SDK install\r
862 # that Visual Studio performs happens to select that feature varies with the VS\r
863 # and SDK version - when it does, WPT lands in\r
864 # %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK\r
865 # puts that directory on the machine PATH itself - so this step DETECTS first\r
866 # and only falls back to installing the ADK (winget owns the versioned download\r
867 # URL, which makes it the reliable source) when nothing is there. That fallback\r
868 # is a large download; to install just the toolkit instead, run the standalone\r
869 # SDK setup with\r
870 #     winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q\r
871 #\r
872 # There is also a newer WPA in the Microsoft Store (`winget install --id\r
873 # 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is\r
874 # not installed here: the Store package needs an interactive, signed-in session,\r
875 # which is exactly what this elevated, unattended half does not have.\r
876 #\r
877 # Idempotent and non-fatal - it never aborts provisioning.\r
878 # ---------------------------------------------------------------------------\r
879 Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'\r
880 $WptDirs = @(\r
881     (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),\r
882     (Join-Path $env:ProgramFiles        'Windows Kits\10\Windows Performance Toolkit'),\r
883     (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')\r
884 )\r
885 function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }\r
886 \r
887 $WptDir = Find-WptDir\r
888 if ($WptDir) {\r
889     Write-Host "    OK: WPT already present ($WptDir)" -ForegroundColor Green\r
890 } else {\r
891     try {\r
892         winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r
893             --accept-source-agreements --accept-package-agreements\r
894         Write-Host '    Windows ADK (includes Windows Performance Toolkit) installed.'\r
895         $WptDir = Find-WptDir\r
896     } catch {\r
897         Write-Warning "WPT install failed: $($_.Exception.Message)"\r
898         Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r
899         Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'\r
900     }\r
901 }\r
902 \r
903 if ($WptDir) {\r
904     # Report what actually landed. wpa.exe is the piece people come looking for\r
905     # and it is the one that is absent if a trimmed toolkit ever shows up.\r
906     foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {\r
907         $p = Join-Path $WptDir $tool\r
908         if (Test-Path $p) {\r
909             Write-Host "    $tool $((Get-Item $p).VersionInfo.ProductVersion)"\r
910         } else {\r
911             Write-Warning "$tool is missing from $WptDir"\r
912         }\r
913     }\r
914 \r
915     # The WPT installer normally adds this to the machine PATH itself (and the\r
916     # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for\r
917     # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user\r
918     # one so it also resolves for the non-interactive sshd sessions this box is\r
919     # driven through, which build their environment from the registry PATH.\r
920     # Compared trailing-backslash-insensitively - the installer's own entry has\r
921     # one, and adding a second spelling of the same directory is just noise.\r
922     $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
923     if (-not $m) { $m = '' }\r
924     $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }\r
925     if ($have) {\r
926         Write-Host "    OK: $WptDir already in the machine PATH"\r
927     } else {\r
928         $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }\r
929         [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
930         Write-Host "    Added $WptDir to the machine PATH (restart shells to pick it up)."\r
931     }\r
932 }\r
933 \r
934 \r
935 # ---------------------------------------------------------------------------\r
936 Write-Host "`nAll done." -ForegroundColor Green\r
937 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r
938 \r
939 }\r
940 catch {\r
941     $ExitCode = 1\r
942     Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red\r
943     if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }\r
944     # Only fold in the VS Installer logs when a VS step actually failed; for other\r
945     # steps (e.g. WDK) those logs are stale and misleading, so the message above\r
946     # is what matters.\r
947     if ($_.Exception.Message -match 'VS2022') {\r
948         try { Show-VsSetupLogs } catch {}\r
949     }\r
950 }\r
951 finally {\r
952     try { Stop-Transcript | Out-Null } catch {}\r
953 \r
954     # This log was created by the elevated (admin) process, so by default the\r
955     # non-elevated caller can't delete it (their token has Administrators marked\r
956     # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs\r
957     # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known\r
958     # Users SID, used here so this is locale-independent.\r
959     try {\r
960         if (Test-Path $LogFile) {\r
961             $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')\r
962             $acl  = Get-Acl -Path $LogFile\r
963             $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(\r
964                         $usersSid, 'Modify', 'Allow')\r
965             $acl.AddAccessRule($rule)\r
966             Set-Acl -Path $LogFile -AclObject $acl\r
967         }\r
968     } catch {\r
969         Write-Host "    [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow\r
970     }\r
971 }\r
972 \r
973 exit $ExitCode\r