+if ($WptDir) {\r
+ # Report what actually landed. wpa.exe is the piece people come looking for\r
+ # and it is the one that is absent if a trimmed toolkit ever shows up.\r
+ foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {\r
+ $p = Join-Path $WptDir $tool\r
+ if (Test-Path $p) {\r
+ Write-Host " $tool $((Get-Item $p).VersionInfo.ProductVersion)"\r
+ } else {\r
+ Write-Warning "$tool is missing from $WptDir"\r
+ }\r
+ }\r
+\r
+ # The WPT installer normally adds this to the machine PATH itself (and the\r
+ # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for\r
+ # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user\r
+ # one so it also resolves for the non-interactive sshd sessions this box is\r
+ # driven through, which build their environment from the registry PATH.\r
+ # Compared trailing-backslash-insensitively - the installer's own entry has\r
+ # one, and adding a second spelling of the same directory is just noise.\r
+ $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
+ if (-not $m) { $m = '' }\r
+ $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }\r
+ if ($have) {\r
+ Write-Host " OK: $WptDir already in the machine PATH"\r
+ } else {\r
+ $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }\r
+ [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
+ Write-Host " Added $WptDir to the machine PATH (restart shells to pick it up)."\r
+ }\r
+}\r
+\r
+# ---------------------------------------------------------------------------\r
+# ETW collection rights for an ordinary account\r
+#\r
+# Out of the box, xperf and wpr only work elevated, and they fail in two\r
+# different ways for a standard user - because two different things are missing:\r
+#\r
+# xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)"\r
+# wpr -start GeneralProfile\r
+# -> "Failed to enable the policy to profile system\r
+# performance." (0xc5585011)\r
+#\r
+# 1. Creating or controlling ANY event tracing session - even a user-mode one\r
+# naming a single provider - is checked against the security descriptor ETW\r
+# keeps per provider GUID under\r
+# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The default grants the\r
+# session-control rights (TRACELOG_CREATE_ONDISK, TRACELOG_CREATE_REALTIME,\r
+# TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to SYSTEM, Administrators, the\r
+# service accounts, and BUILTIN\Performance Log Users - and to nobody else.\r
+# That group is the supported hook; its own description says members "may\r
+# ... enable trace providers, and collect event traces".\r
+#\r
+# 2. Switching on the kernel/system trace provider on top of that needs the\r
+# SeSystemProfilePrivilege user right ("Profile system performance"), held by\r
+# default only by Administrators and NT SERVICE\WdiServiceHost. That is the\r
+# one wpr names in its error, and the one xperf trips over for -on base.\r
+#\r
+# So grant the privilege to the GROUP and then put the account in the group:\r
+# membership alone becomes the switch, and enabling the next account is one\r
+# `net localgroup` away with no policy edit.\r
+#\r
+# Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU\r
+# sampling nor walking stacks in your own processes, and it is equivalent to\r
+# handing out administrator.\r
+#\r
+# THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership\r
+# are baked into the access token at LOGON, and UAC hands an administrator a\r
+# filtered token that keeps just five harmless privileges - so an admin's\r
+# ordinary shell still cannot trace, however the policy reads. Running as a\r
+# standard user is what makes this work.\r
+#\r
+# For the same reason nothing here takes effect in an already-open session: the\r
+# account has to sign out and back in. Any NEW logon does it - an ssh login into\r
+# this box is one, which is the quick way to check without dropping the desktop.\r
+#\r
+# Analysis never needed any of this: wpa.exe opens an existing .etl as a plain\r
+# user. This step is only about collection.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'ETW collection rights (non-elevated xperf / wpr)'\r
+$PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users\r
+try {\r
+ # --- The user right, granted to the group ---\r
+ $existing = Get-AccountRight $PerfLogUsersSid\r
+ if ($existing -contains 'SeSystemProfilePrivilege') {\r
+ Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege'\r
+ } else {\r
+ Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'\r
+ Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'\r
+ }\r
+\r
+ # --- The membership ---\r
+ # Fall back to the console user when the caller did not name one: with\r
+ # over-the-shoulder elevation that is the person who started\r
+ # setup-windows.bat, which is who wants to trace.\r
+ $target = $TraceUser\r
+ if (-not $target) {\r
+ $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName\r
+ if ($target) { Write-Host " No -TraceUser given; using the console user $target" }\r
+ }\r
+\r
+ if (-not $target) {\r
+ Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'\r
+ Write-Warning 'The user right is in place, so this is the only step left:'\r
+ Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add'\r
+ } else {\r
+ # Resolve to a SID first: it validates the name, and it is what the\r
+ # membership check compares, so a member spelled ".\claude" in one place\r
+ # and "LATISLAB\claude" in another is still recognised as the same account.\r
+ $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(\r
+ [System.Security.Principal.SecurityIdentifier])\r
+\r
+ # By SID, never by name: "Performance Log Users" is localised, and\r
+ # Get-LocalGroup -SID is how this stays correct on a non-English box.\r
+ $group = Get-LocalGroup -SID $PerfLogUsersSid\r
+\r
+ # Get-LocalGroupMember throws on a group holding a SID that no longer\r
+ # resolves (a known Windows 10 bug), so a failure to READ the membership\r
+ # must not stop us from writing it - fall through and let the add report.\r
+ $already = $false\r
+ try {\r
+ $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |\r
+ Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0\r
+ } catch {\r
+ Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray\r
+ }\r
+\r
+ if ($already) {\r
+ Write-Host " OK: $target is already in $($group.Name)"\r
+ } else {\r
+ try {\r
+ Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value\r
+ } catch {\r
+ # "already a member" is only reachable when the enumeration above\r
+ # failed, and is not an error. Matched on the type NAME rather\r
+ # than in a typed catch clause: catch types are resolved when the\r
+ # script is PARSED, before the LocalAccounts module has been\r
+ # autoloaded, so naming the type there is a parse error that\r
+ # would take the whole script down.\r
+ if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }\r
+ }\r
+ Write-Host " Added $target to $($group.Name)"\r
+ }\r
+\r
+ Write-Host ''\r
+ Write-Host " $target must sign out and back in before this takes effect." -ForegroundColor Yellow\r
+ Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow\r
+ Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow\r
+ Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow\r
+ }\r
+} catch {\r
+ Write-Warning "ETW rights setup failed: $($_.Exception.Message)"\r
+ Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'\r
+ Write-Warning '"Profile system performance" > add Performance Log Users, then'\r
+ Write-Warning ' net localgroup "Performance Log Users" <user> /add'\r
+}\r
+\r