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 - 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
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
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
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
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
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
49 $ErrorActionPreference = 'Stop'
\r
51 function Write-Step([string]$Msg) {
\r
52 Write-Host "`n==> $Msg" -ForegroundColor Cyan
\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
60 if ($Code -eq 3010) {
\r
61 Write-Host " [reboot required after $Step]" -ForegroundColor Yellow
\r
65 # ---------------------------------------------------------------------------
\r
66 # User rights assignment (LSA account rights)
\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
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
83 using System.ComponentModel;
\r
84 using System.Runtime.InteropServices;
\r
86 public static class LsaRights
\r
88 [StructLayout(LayoutKind.Sequential)]
\r
89 private struct LSA_UNICODE_STRING
\r
91 public ushort Length;
\r
92 public ushort MaximumLength;
\r
93 public IntPtr Buffer;
\r
96 [StructLayout(LayoutKind.Sequential)]
\r
97 private struct LSA_OBJECT_ATTRIBUTES
\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
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
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
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
119 [DllImport("advapi32.dll")]
\r
120 private static extern uint LsaClose(IntPtr policyHandle);
\r
122 [DllImport("advapi32.dll")]
\r
123 private static extern uint LsaFreeMemory(IntPtr buffer);
\r
125 [DllImport("advapi32.dll")]
\r
126 private static extern int LsaNtStatusToWinError(uint status);
\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
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
136 private static IntPtr OpenPolicy()
\r
138 LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES();
\r
139 attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
\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
147 public static string[] Get(byte[] sid)
\r
149 IntPtr policy = OpenPolicy();
\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
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
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
169 finally { LsaFreeMemory(rights); }
\r
171 finally { LsaClose(policy); }
\r
174 public static void Add(byte[] sid, string right)
\r
176 IntPtr policy = OpenPolicy();
\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
186 uint status = LsaAddAccountRights(policy, sid, rights, 1);
\r
187 if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }
\r
189 finally { Marshal.FreeHGlobal(rights[0].Buffer); }
\r
191 finally { LsaClose(policy); }
\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
204 function Get-AccountRight([string]$Sid) {
\r
205 Initialize-LsaRightsType
\r
206 return [LsaRights]::Get((Get-SidBytes $Sid))
\r
209 function Grant-AccountRight([string]$Sid, [string]$Right) {
\r
210 Initialize-LsaRightsType
\r
211 [LsaRights]::Add((Get-SidBytes $Sid), $Right)
\r
214 # ---------------------------------------------------------------------------
\r
215 # ETW provider-GUID access control
\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
227 using System.Runtime.InteropServices;
\r
229 public static class EtwAcl
\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
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
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
252 # READ_CONTROL (0x20000) and SYNCHRONIZE (0x100000) go with them - the SYSTEM and
\r
253 # Administrators entries on this GUID carry 0x120FFF. Without READ_CONTROL the
\r
254 # group cannot read the descriptor back, which makes EventAccessQuery useless as
\r
255 # a check on whether the grant landed: it answers "access denied" either way.
\r
256 $EtwControllerRights = 0x120FE1
\r
258 function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) {
\r
259 Initialize-EtwAclType
\r
261 # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing
\r
262 # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which
\r
263 # on the kernel logger means removing the entries Windows itself relies on.
\r
264 $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true)
\r
265 if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) }
\r
268 function Get-EtwGuidSddl([string]$Guid) {
\r
269 Initialize-EtwAclType
\r
272 [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size)
\r
273 if ($size -eq 0) { return $null }
\r
274 $buf = New-Object byte[] $size
\r
275 if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null }
\r
276 return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access')
\r
279 function Show-VsSetupLogs {
\r
280 # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because
\r
281 # this script runs elevated, that %TEMP% belongs to the elevated user and is
\r
282 # readable here even when it is NOT readable by the non-elevated caller. Fold
\r
283 # only the NEWEST installer + bootstrapper log into the transcript (the setup
\r
284 # engine log is where per-component / product errors actually appear) and
\r
285 # keep it short so the transcript stays readable.
\r
286 Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan
\r
287 $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |
\r
288 Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }
\r
290 $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
291 $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
292 $picks = $picks | Where-Object { $_ }
\r
294 Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow
\r
297 foreach ($l in $picks) {
\r
298 Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow
\r
299 Get-Content $l.FullName -Tail 40
\r
303 function Invoke-VsModify {
\r
304 # Run one VS install/modify pass for a named group of components. Splitting
\r
305 # the install into separate passes makes it obvious WHICH group fails: each
\r
306 # call prints its label and exit code before Assert-ExitCode throws.
\r
311 Write-Step "VS2022: $Label"
\r
312 $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '
\r
313 # --installPath must be quoted: it contains spaces ("C:\Program Files\...").
\r
314 # Windows PowerShell 5.1's Start-Process does not quote array elements, so we
\r
315 # hand-build a single string. Component IDs / flags have no spaces.
\r
316 $common = '--includeRecommended --quiet --norestart --wait'
\r
317 if ($script:InstallPath) {
\r
318 $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"
\r
320 # No existing install yet -> this first pass performs the base install.
\r
321 $argString = "$addStr $common"
\r
323 Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray
\r
324 $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow
\r
325 Write-Host " exit code: $($p.ExitCode)"
\r
326 Assert-ExitCode $p.ExitCode "VS2022 ($Label)"
\r
328 # After the first (fresh) install, re-detect the install path so subsequent
\r
329 # passes use `modify`.
\r
330 if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {
\r
331 $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |
\r
332 Select-Object -First 1
\r
336 # ---------------------------------------------------------------------------
\r
337 # This runs in a separate elevated window that closes the moment it exits, so
\r
338 # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror
\r
339 # all output to a log next to the script and exit with a real code so the
\r
340 # caller can detect success/failure and show the log.
\r
341 # ---------------------------------------------------------------------------
\r
342 $LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log'
\r
344 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}
\r
348 # ---------------------------------------------------------------------------
\r
349 # ETW collection rights for an ordinary account
\r
351 # Out of the box, xperf and wpr only work elevated. THREE separate things stand
\r
352 # in a standard user's way, and each has its own error:
\r
354 # xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)"
\r
355 # wpr -start GeneralProfile
\r
356 # -> "Failed to enable the policy to profile system
\r
357 # performance." (0xc5585011)
\r
359 # 1. Creating or controlling ANY event tracing session - even a user-mode one
\r
360 # naming a single provider - is checked against the security descriptor ETW
\r
361 # keeps per provider GUID under
\r
362 # HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor
\r
363 # grants the session-control rights (TRACELOG_CREATE_ONDISK,
\r
364 # TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to
\r
365 # SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log
\r
366 # Users - and to nobody else. That group is the supported hook; its own
\r
367 # description says members "may ... enable trace providers, and collect event
\r
370 # 2. Switching on the kernel/system trace provider on top of that needs the
\r
371 # SeSystemProfilePrivilege user right ("Profile system performance"), held by
\r
372 # default only by Administrators and NT SERVICE\WdiServiceHost. That is the
\r
373 # one wpr names in its error.
\r
375 # 3. The kernel logger is not covered by that default descriptor. Its own GUID -
\r
376 # SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries
\r
377 # an explicit descriptor that does not mention Performance Log Users, so 1 and
\r
378 # 2 are not enough by themselves. Measured on this box with both in place: a
\r
379 # user-mode session starts (exit 0) and the account holds the privilege, and
\r
380 # `xperf -on base` still answers "NT Kernel Logger: Access is denied" while
\r
381 # wpr's error changes from the policy message above to a bare 0x80070005.
\r
382 # Even READING that descriptor comes back access-denied, which is the tell. So
\r
383 # add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER
\r
384 # is the right that names this particular session.
\r
386 # The privilege and the ACE both go to the GROUP, and the account then goes into
\r
387 # the group: membership alone becomes the switch, and enabling the next account
\r
388 # is one `net localgroup` away with no policy or registry edit.
\r
390 # What this costs, stated plainly: a member of that group can capture
\r
391 # system-wide kernel traces - process, image, file and registry activity across
\r
392 # every account on the box, paths and command lines included. That is what the
\r
393 # group is for, and it is the price of collecting a trace without a UAC prompt.
\r
395 # Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU
\r
396 # sampling nor walking stacks in your own processes, and it is equivalent to
\r
397 # handing out administrator.
\r
399 # THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership
\r
400 # are baked into the access token at LOGON, and UAC hands an administrator a
\r
401 # filtered token that keeps just five harmless privileges - so an admin's
\r
402 # ordinary shell still cannot trace, however the policy reads. Running as a
\r
403 # standard user is what makes this work.
\r
405 # For the same reason 1 and 2 do not take effect in an already-open session: the
\r
406 # account has to sign out and back in. Any NEW logon does it - an ssh login into
\r
407 # this box is one, which is the quick way to check without dropping the desktop.
\r
408 # The ACE in 3 is machine state rather than token state, so a logon does nothing
\r
409 # for it. ETW reads these descriptors into a cache, so a REBOOT is what is
\r
410 # expected to put the change into effect: with the ACE written and readable in
\r
411 # the descriptor, xperf -on base was still answering "Access is denied" from a
\r
412 # fresh shell on the running system. So on a first run, plan on both - a new
\r
413 # logon for 1 and 2, a reboot for 3.
\r
415 # Analysis never needed any of this: wpa.exe opens an existing .etl as a plain
\r
416 # user. This step is only about collection.
\r
417 # ---------------------------------------------------------------------------
\r
418 Write-Step 'ETW collection rights (non-elevated xperf / wpr)'
\r
419 $PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users
\r
420 # SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on
\r
421 # and wpr both drive. Fixed by contract, from evntrace.h.
\r
422 $SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939'
\r
424 # --- The user right, granted to the group ---
\r
425 $existing = Get-AccountRight $PerfLogUsersSid
\r
426 if ($existing -contains 'SeSystemProfilePrivilege') {
\r
427 Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege'
\r
429 Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'
\r
430 Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'
\r
433 # --- The kernel logger's own descriptor ---
\r
434 # Safe to repeat: a second ACE for the same SID unions to the same access.
\r
435 # Kept in its own try so that a failure here still leaves the group
\r
436 # membership below to be done - user-mode sessions work without it.
\r
438 # ETW reads these descriptors out of the registry into a cache, so a REBOOT
\r
439 # is what puts a change here into effect - not a new logon, which is what the
\r
440 # group membership and the privilege need. Both, on a first run.
\r
442 Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights
\r
443 Write-Host (" Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights)
\r
444 $sddl = Get-EtwGuidSddl $SystemTraceControlGuid
\r
445 if ($sddl) { Write-Host " kernel logger DACL is now $sddl" -ForegroundColor DarkGray }
\r
447 Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)"
\r
448 Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."'
\r
451 # --- The membership ---
\r
452 # Fall back to the console user when the caller did not name one: with
\r
453 # over-the-shoulder elevation that is the person who started
\r
454 # setup-windows.bat, which is who wants to trace.
\r
455 $target = $TraceUser
\r
456 if (-not $target) {
\r
457 $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName
\r
458 if ($target) { Write-Host " No -TraceUser given; using the console user $target" }
\r
461 if (-not $target) {
\r
462 Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'
\r
463 Write-Warning 'The user right is in place, so this is the only step left:'
\r
464 Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add'
\r
466 # Resolve to a SID first: it validates the name, and it is what the
\r
467 # membership check compares, so a member spelled ".\claude" in one place
\r
468 # and "LATISLAB\claude" in another is still recognised as the same account.
\r
469 $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(
\r
470 [System.Security.Principal.SecurityIdentifier])
\r
472 # By SID, never by name: "Performance Log Users" is localised, and
\r
473 # Get-LocalGroup -SID is how this stays correct on a non-English box.
\r
474 $group = Get-LocalGroup -SID $PerfLogUsersSid
\r
476 # Get-LocalGroupMember throws on a group holding a SID that no longer
\r
477 # resolves (a known Windows 10 bug), so a failure to READ the membership
\r
478 # must not stop us from writing it - fall through and let the add report.
\r
481 $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |
\r
482 Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0
\r
484 Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray
\r
488 Write-Host " OK: $target is already in $($group.Name)"
\r
491 Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value
\r
493 # "already a member" is only reachable when the enumeration above
\r
494 # failed, and is not an error. Matched on the type NAME rather
\r
495 # than in a typed catch clause: catch types are resolved when the
\r
496 # script is PARSED, before the LocalAccounts module has been
\r
497 # autoloaded, so naming the type there is a parse error that
\r
498 # would take the whole script down.
\r
499 if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }
\r
501 Write-Host " Added $target to $($group.Name)"
\r
505 Write-Host " $target must sign out and back in for the group and the privilege," -ForegroundColor Yellow
\r
506 Write-Host ' and the box must be REBOOTED for the kernel logger ACE (ETW caches it).' -ForegroundColor Yellow
\r
507 Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow
\r
508 Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow
\r
509 Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow
\r
512 Write-Warning "ETW rights setup failed: $($_.Exception.Message)"
\r
513 Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'
\r
514 Write-Warning '"Profile system performance" > add Performance Log Users, then'
\r
515 Write-Warning ' net localgroup "Performance Log Users" <user> /add'
\r
518 if ($EtwRightsOnly) {
\r
519 # `exit` inside the try still runs the finally below, so the transcript is
\r
520 # stopped and the log is left readable by the non-elevated caller.
\r
521 Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green
\r
526 # ---------------------------------------------------------------------------
\r
527 # Base tools via winget
\r
528 # ---------------------------------------------------------------------------
\r
530 # ---------------------------------------------------------------------------
\r
533 # Present by default on Windows 10 1809+ / Windows 11, but removable, and absent
\r
534 # from some Server images. Two things below want it: rsync does not speak ssh
\r
535 # itself, it execs an ssh binary, and the release's own ssh.exe links against the
\r
536 # libcrypto.dll this capability puts in System32. It also owns the ssh-agent
\r
537 # service configured next, so a missing client is why that step would fail.
\r
539 # Non-fatal, like the server half below: a box that cannot have it should still
\r
540 # finish provisioning.
\r
541 # ---------------------------------------------------------------------------
\r
542 Write-Step 'OpenSSH Client'
\r
544 $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |
\r
545 Select-Object -First 1
\r
547 Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'
\r
548 } elseif ($sshc.State -eq 'Installed') {
\r
549 Write-Host " OK: $($sshc.Name) already installed"
\r
551 Write-Host " Installing $($sshc.Name) ..."
\r
552 $r = Add-WindowsCapability -Online -Name $sshc.Name
\r
553 if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Client]' -ForegroundColor Yellow }
\r
556 Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"
\r
559 # ---------------------------------------------------------------------------
\r
561 # ---------------------------------------------------------------------------
\r
562 Write-Step 'Enabling ssh-agent'
\r
563 Set-Service -Name ssh-agent -StartupType Automatic
\r
564 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }
\r
566 # ---------------------------------------------------------------------------
\r
567 # OpenSSH Server (sshd)
\r
569 # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the
\r
570 # transport rsync rides on when seeding test data in. Ships with Windows 10
\r
571 # 1809+ / Windows 11 as an on-demand capability, so no third-party install.
\r
573 # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall
\r
574 # rule; we verify and create it if missing (it is absent on some images).
\r
576 # Non-fatal: a box that can't run sshd should still finish provisioning.
\r
577 # ---------------------------------------------------------------------------
\r
578 Write-Step 'OpenSSH Server (sshd)'
\r
580 $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |
\r
581 Select-Object -First 1
\r
583 Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'
\r
585 if ($sshd.State -ne 'Installed') {
\r
586 Write-Host " Installing $($sshd.Name) ..."
\r
587 $r = Add-WindowsCapability -Online -Name $sshd.Name
\r
588 if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Server]' -ForegroundColor Yellow }
\r
590 Write-Host " OK: $($sshd.Name) already installed"
\r
593 Set-Service -Name sshd -StartupType Automatic
\r
594 if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }
\r
595 Write-Host ' sshd: Automatic + running'
\r
597 # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and
\r
598 # bridged adapters are frequently classified Public, and the capability's
\r
599 # own rule is Private-only on some images, which is what leaves a plainly
\r
600 # running sshd plainly unreachable.
\r
602 # OpenSSH-Server-In-TCP is the name the capability itself uses, so this
\r
603 # WIDENS that rule rather than adding a second one next to it. Creating
\r
604 # our own under a different name would leave the narrow rule in place and
\r
605 # the box still unreachable on a Public-classified adapter; creating one
\r
606 # under the same name would collide. Adopt it if present, create it if not.
\r
607 $ruleName = 'OpenSSH-Server-In-TCP'
\r
608 if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {
\r
609 Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any
\r
610 Write-Host " Widened firewall rule $ruleName to all profiles"
\r
612 New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `
\r
613 -Enabled True -Direction Inbound -Protocol TCP -Action Allow `
\r
614 -LocalPort 22 -Profile Any | Out-Null
\r
615 Write-Host " Added firewall rule $ruleName (TCP 22, all profiles)"
\r
619 Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"
\r
622 # ---------------------------------------------------------------------------
\r
623 # rsync for Windows (github.com/nuket/rsync-windows)
\r
625 # Windows' OpenSSH ships the transport only - no rsync - so pushing test data
\r
626 # from a Linux box needs an rsync.exe on the Windows side.
\r
628 # The release is one zip per architecture - rsync-windows-x64.zip and
\r
629 # rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the
\r
630 # licence texts under exactly those names. Both exes are installed, together:
\r
631 # rsync.exe prefers an ssh.exe in its own directory, and the release's build is
\r
632 # what makes a push FROM this box run at line rate. The ssh.exe Windows ships
\r
633 # reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the
\r
634 # link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same
\r
635 # known_hosts - and a bare `ssh` still resolves to the in-box client, which sits
\r
636 # ahead of C:\Tools\rsync on the machine PATH.
\r
638 # That ssh.exe links against the libcrypto.dll the OpenSSH Client capability
\r
639 # above puts in System32: Windows' own LibreSSL, and the fast one, since it uses
\r
640 # AES-NI. No copy of it ships in the zip, so where the capability is missing we
\r
641 # unpack rsync alone rather than an ssh.exe that will not start.
\r
643 # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is
\r
644 # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes
\r
645 # the client-side --rsync-path escape hatch painful to quote. Added to the
\r
646 # MACHINE PATH so it resolves for every account, including the non-interactive
\r
647 # sshd session, which builds its environment from the machine + user registry
\r
648 # PATH rather than from a login shell.
\r
650 # Non-fatal: a download failure only warns.
\r
651 # ---------------------------------------------------------------------------
\r
652 Write-Step 'rsync for Windows'
\r
653 $RsyncRepo = 'nuket/rsync-windows'
\r
654 $RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }
\r
655 # The /releases/latest/download/ redirect rather than the API: unauthenticated
\r
656 # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a
\r
657 # shared NAT can genuinely exhaust, and the redirect costs none of that budget.
\r
658 # To hold a box on a known build, pin the tag instead:
\r
659 # .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset
\r
660 $RsyncUrl = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"
\r
661 $RsyncDir = 'C:\Tools\rsync'
\r
663 New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null
\r
664 $RsyncExe = Join-Path $RsyncDir 'rsync.exe'
\r
666 # Does the release's ssh.exe have the libcrypto it needs? Decided before the
\r
667 # download so the answer can also gate what comes out of the zip.
\r
668 $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'
\r
669 $WantSsh = Test-Path $SysCrypto
\r
670 if (-not $WantSsh) {
\r
671 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
673 $v = (Get-Item $SysCrypto).VersionInfo.FileVersion
\r
674 if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {
\r
675 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
679 # Download and unpack beside the targets, not over them, so an interrupted
\r
680 # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch
\r
681 # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive
\r
682 # refuses any other extension outright ("*.download is not a supported
\r
683 # archive file format"), where PowerShell 7 just reads the file.
\r
684 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
\r
685 $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"
\r
686 Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing
\r
687 Write-Host " Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"
\r
689 # Verify against the .sha256 published beside it. Same origin, so this is an
\r
690 # integrity check on the transfer rather than a defence against a hostile
\r
691 # release - but a truncated or proxy-mangled download is the failure that
\r
692 # actually happens, and it fails here instead of mid-transfer later.
\r
694 # -OutFile, not .Content: GitHub serves the .sha256 as
\r
695 # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather
\r
696 # than a string for any non-text content type, so .Content would compare the
\r
697 # first BYTE against the hash and fail on every correct download.
\r
698 $tmpSha = "$tmpZip.sha256"
\r
699 Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing
\r
700 $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()
\r
701 Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue
\r
702 $got = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()
\r
703 if ($want -and $want -ne $got) {
\r
704 Remove-Item $tmpZip -Force
\r
705 throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"
\r
707 Write-Host " SHA-256 verified: $got"
\r
709 # Unpack to a scratch directory and move out the files we asked for, rather
\r
710 # than expanding straight over the install directory: the zip is the unit
\r
711 # that was checksummed, and this way a future release adding something to it
\r
712 # cannot quietly drop that something onto the machine PATH.
\r
713 $unpack = Join-Path $RsyncDir '.unpack'
\r
714 if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }
\r
715 Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force
\r
716 Remove-Item $tmpZip -Force
\r
717 foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {
\r
718 $src = Join-Path $unpack $f
\r
719 if (-not (Test-Path $src)) { continue }
\r
720 if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }
\r
721 Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force
\r
723 Remove-Item -Recurse -Force $unpack
\r
724 Write-Host " Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"
\r
726 # Machine PATH (HKLM environment). Idempotent: only appends if absent.
\r
727 $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')
\r
728 if (-not $m) { $m = '' }
\r
729 if (($m -split ';') -notcontains $RsyncDir) {
\r
730 $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }
\r
731 [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')
\r
732 Write-Host " Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."
\r
733 # sshd caches the environment it was started with, so an already-running
\r
734 # service would not see the new PATH until restarted.
\r
735 if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {
\r
736 Restart-Service sshd
\r
737 Write-Host ' Restarted sshd so it inherits the updated machine PATH.'
\r
740 Write-Host " OK: $RsyncDir already in the machine PATH"
\r
743 & $RsyncExe --version | Select-Object -First 1
\r
745 Write-Warning "rsync install failed: $($_.Exception.Message)"
\r
746 Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"
\r
747 Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."
\r
750 # ---------------------------------------------------------------------------
\r
751 # Visual Studio 2022 Community
\r
752 # ---------------------------------------------------------------------------
\r
753 $TempDir = Join-Path $env:TEMP 'dev_install'
\r
754 New-Item -ItemType Directory -Force -Path $TempDir | Out-Null
\r
756 # Component IDs split into independent groups so each can be installed in its
\r
757 # own pass. The base group is the known-good set; Clang and the Windows XP
\r
758 # toolset are layered on afterwards so a failure clearly identifies the culprit.
\r
759 # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community
\r
760 $BaseComponents = @(
\r
761 # Core C++ desktop workload
\r
762 'Microsoft.VisualStudio.Workload.NativeDesktop'
\r
764 # Spectre-mitigated MSVC runtime libs
\r
765 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'
\r
766 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'
\r
768 # Spectre-mitigated ATL (needed for many driver/COM projects)
\r
769 'Microsoft.VisualStudio.Component.VC.ATL.Spectre'
\r
771 # Windows 11 SDK — build number must match the WDK below
\r
772 'Microsoft.VisualStudio.Component.Windows11SDK.26100'
\r
774 # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT
\r
775 # install this (it only prompts interactively), so it must be added here.
\r
776 'Component.Microsoft.Windows.DriverKit'
\r
779 # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang
\r
780 # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.
\r
781 $ClangComponents = @(
\r
782 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'
\r
783 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'
\r
786 # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141
\r
787 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;
\r
788 # WinXP layers the XP-compatible CRT/SDK on top of it.
\r
790 'Microsoft.VisualStudio.Component.VC.v141.x86.x64'
\r
791 'Microsoft.VisualStudio.Component.WinXP'
\r
794 # Detect an existing VS install via vswhere (ships with the VS Installer).
\r
795 # These are referenced by Invoke-VsModify via $script: scope.
\r
796 $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
\r
797 $InstallPath = $null
\r
798 if (Test-Path $VsWhere) {
\r
799 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
800 Select-Object -First 1
\r
803 Write-Step 'Downloading VS2022 Community bootstrapper'
\r
804 $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'
\r
805 $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'
\r
806 Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing
\r
808 # Install in three sequential passes. The base set is installed first (this is
\r
809 # the configuration that previously worked); Clang and the XP toolset are added
\r
810 # afterwards. If one fails, its label pinpoints which group is responsible.
\r
811 Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents
\r
812 Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents
\r
813 Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents
\r
815 # ---------------------------------------------------------------------------
\r
816 # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped
\r
817 # it and the failure only surfaced at build time, so check on disk and fail
\r
818 # loudly here instead.
\r
819 # ---------------------------------------------------------------------------
\r
820 Write-Step 'Verifying v141 / XP toolset'
\r
821 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
822 Select-Object -First 1
\r
823 $V141 = if ($InstallPath) {
\r
824 Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
\r
825 Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1
\r
828 Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green
\r
830 Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'
\r
831 Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'
\r
832 Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'
\r
833 Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools'
\r
836 # ---------------------------------------------------------------------------
\r
837 # Windows Driver Kit (WDK 10.0.26100)
\r
838 # Build 26100 matches the Windows 11 SDK installed above.
\r
839 # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.
\r
840 # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").
\r
841 # ---------------------------------------------------------------------------
\r
842 $WdkVersion = '10.0.26100'
\r
843 $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `
\r
844 -ErrorAction SilentlyContinue).WdkBinRootVersioned
\r
846 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {
\r
847 # Re-running wdksetup.exe for an already-present version returns exit code
\r
848 # 2008 (maintenance mode / nothing to do), which is not a real failure.
\r
849 Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"
\r
851 Write-Step 'Downloading WDK installer'
\r
852 $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869'
\r
853 $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'
\r
854 Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing
\r
856 Write-Step 'Installing WDK'
\r
857 $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow
\r
858 Write-Host " WDK installer exit code: $($proc.ExitCode)"
\r
859 if ($proc.ExitCode -eq 2008) {
\r
860 # 2008 = the WDK is already present; the installer has nothing to do.
\r
861 Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow
\r
863 Assert-ExitCode $proc.ExitCode 'WDK'
\r
867 # ---------------------------------------------------------------------------
\r
868 # Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer
\r
869 # (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.
\r
871 # WPA is NOT a Visual Studio component and has no relationship to VS's own
\r
872 # Performance Profiler (a separate, .diagsession-based tool that cannot open an
\r
873 # .etl). It ships in exactly two places: as an optional FEATURE of the Windows
\r
874 # SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and
\r
875 # in the Windows ADK, which bundles the same toolkit. Whether the SDK install
\r
876 # that Visual Studio performs happens to select that feature varies with the VS
\r
877 # and SDK version - when it does, WPT lands in
\r
878 # %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK
\r
879 # puts that directory on the machine PATH itself - so this step DETECTS first
\r
880 # and only falls back to installing the ADK (winget owns the versioned download
\r
881 # URL, which makes it the reliable source) when nothing is there. That fallback
\r
882 # is a large download; to install just the toolkit instead, run the standalone
\r
884 # winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q
\r
886 # There is also a newer WPA in the Microsoft Store (`winget install --id
\r
887 # 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is
\r
888 # not installed here: the Store package needs an interactive, signed-in session,
\r
889 # which is exactly what this elevated, unattended half does not have.
\r
891 # Idempotent and non-fatal - it never aborts provisioning.
\r
892 # ---------------------------------------------------------------------------
\r
893 Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'
\r
895 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),
\r
896 (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit'),
\r
897 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')
\r
899 function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }
\r
901 $WptDir = Find-WptDir
\r
903 Write-Host " OK: WPT already present ($WptDir)" -ForegroundColor Green
\r
906 winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `
\r
907 --accept-source-agreements --accept-package-agreements
\r
908 Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.'
\r
909 $WptDir = Find-WptDir
\r
911 Write-Warning "WPT install failed: $($_.Exception.Message)"
\r
912 Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'
\r
913 Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'
\r
918 # Report what actually landed. wpa.exe is the piece people come looking for
\r
919 # and it is the one that is absent if a trimmed toolkit ever shows up.
\r
920 foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {
\r
921 $p = Join-Path $WptDir $tool
\r
922 if (Test-Path $p) {
\r
923 Write-Host " $tool $((Get-Item $p).VersionInfo.ProductVersion)"
\r
925 Write-Warning "$tool is missing from $WptDir"
\r
929 # The WPT installer normally adds this to the machine PATH itself (and the
\r
930 # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for
\r
931 # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user
\r
932 # one so it also resolves for the non-interactive sshd sessions this box is
\r
933 # driven through, which build their environment from the registry PATH.
\r
934 # Compared trailing-backslash-insensitively - the installer's own entry has
\r
935 # one, and adding a second spelling of the same directory is just noise.
\r
936 $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')
\r
937 if (-not $m) { $m = '' }
\r
938 $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }
\r
940 Write-Host " OK: $WptDir already in the machine PATH"
\r
942 $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }
\r
943 [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')
\r
944 Write-Host " Added $WptDir to the machine PATH (restart shells to pick it up)."
\r
949 # ---------------------------------------------------------------------------
\r
950 # Intel VTune Profiler - reported, not installed
\r
952 # Deliberately NOT automated, unlike everything above. The offline installer is
\r
953 # a ~750 MB download from a URL carrying a per-release GUID
\r
954 # (registrationcenter-download.intel.com/akdlm/IRC_NAS/<guid>/intel-vtune-<ver>_offline.exe)
\r
955 # with no "latest" redirect behind it, so every new build means editing a
\r
956 # hard-coded link in here - and it is only worth having on Intel silicon, since
\r
957 # hardware event-based sampling reads Intel PMU counters. Not a good trade for a
\r
958 # script that has to keep working unattended on any box.
\r
960 # So this step only reports. To install it, take the Windows offline installer
\r
962 # https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html
\r
963 # and run it elevated; it installs unattended with
\r
964 # intel-vtune-<version>_offline.exe -a --silent --cli --eula accept
\r
965 # ---------------------------------------------------------------------------
\r
966 Write-Step 'Intel VTune Profiler (status only)'
\r
967 $UninstallKeys = @(
\r
968 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
\r
969 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
\r
971 $vtune = Get-ItemProperty $UninstallKeys -ErrorAction SilentlyContinue |
\r
972 Where-Object { $_.DisplayName -match 'VTune' } |
\r
973 Select-Object -First 1
\r
975 Write-Host " Installed: $($vtune.DisplayName.Trim()) $($vtune.DisplayVersion)" -ForegroundColor Green
\r
976 # The oneAPI layout keeps a `latest` junction beside the versioned directory,
\r
977 # so this path stays right across upgrades.
\r
978 $VTuneCli = Join-Path $vtune.InstallLocation 'vtune\latest\bin64\vtune.exe'
\r
979 if (Test-Path $VTuneCli) { Write-Host " CLI: $VTuneCli" }
\r
981 Write-Host ' Not installed.' -ForegroundColor Yellow
\r
982 Write-Host ' https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html' -ForegroundColor Yellow
\r
983 $cpu = (Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1).Manufacturer
\r
984 if ($cpu -and $cpu -notmatch 'Intel') {
\r
985 Write-Host " (This CPU reports itself as '$cpu' - VTune's hardware event-based sampling wants Intel silicon.)" -ForegroundColor Yellow
\r
989 # ---------------------------------------------------------------------------
\r
990 Write-Host "`nAll done." -ForegroundColor Green
\r
991 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'
\r
996 Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red
\r
997 if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }
\r
998 # Only fold in the VS Installer logs when a VS step actually failed; for other
\r
999 # steps (e.g. WDK) those logs are stale and misleading, so the message above
\r
1000 # is what matters.
\r
1001 if ($_.Exception.Message -match 'VS2022') {
\r
1002 try { Show-VsSetupLogs } catch {}
\r
1006 try { Stop-Transcript | Out-Null } catch {}
\r
1008 # This log was created by the elevated (admin) process, so by default the
\r
1009 # non-elevated caller can't delete it (their token has Administrators marked
\r
1010 # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs
\r
1011 # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known
\r
1012 # Users SID, used here so this is locale-independent.
\r
1014 if (Test-Path $LogFile) {
\r
1015 $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')
\r
1016 $acl = Get-Acl -Path $LogFile
\r
1017 $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
\r
1018 $usersSid, 'Modify', 'Allow')
\r
1019 $acl.AddAccessRule($rule)
\r
1020 Set-Acl -Path $LogFile -AclObject $acl
\r
1023 Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow
\r