master
ps1 444 lines 16.9 KB
Raw
1 #Requires -RunAsAdministrator
2
3 [CmdletBinding()]
4 Param (
5 $LogProfile = $null,
6 [switch]$Dump = $false,
7 [switch]$RestartWslReproMode = $false
8 )
9
10 Set-StrictMode -Version Latest
11
12 function Test-WslApplication {
13 param (
14 $Name
15 )
16
17 # Log warning when tool is not present in WSL
18
19 # Capture any output/error from wsl.exe so we can distinguish
20 # between "command not found" and "WSL invocation failed".
21 $wslOutput = & wsl.exe -e sh -lc "command -v $Name >/dev/null 2>&1" 2>&1
22 $exitCode = $LASTEXITCODE
23
24 if ($exitCode -eq 0)
25 {
26 return $true
27 }
28
29 # POSIX shells typically return 1 when command -v does not find the command, but we have seen sh returning 127.
30 if ($exitCode -eq 1 -or $exitCode -eq 127)
31 {
32 Write-Warning "$Name not found in WSL. For a more complete log collection install $Name."
33 return $false
34 }
35
36 # Any other exit code is assumed to indicate WSL itself failed
37 # (e.g., no distro installed, WSL disabled, or other startup error).
38 if (-not [string]::IsNullOrWhiteSpace($wslOutput))
39 {
40 Write-Warning "Unable to check for $Name in WSL. wsl.exe exited with code $exitCode. Output: $wslOutput"
41 }
42 else
43 {
44 Write-Warning "Unable to check for $Name in WSL. wsl.exe exited with code $exitCode."
45 }
46
47 return $false
48 }
49
50 function Collect-WindowsNetworkState {
51 param (
52 $Folder,
53 $ReproStep
54 )
55
56 # Collect host networking state relevant for WSL
57 # Using a try/catch for commands below, as some of them do not exist on all OS versions
58
59 try { Get-NetAdapter -includeHidden | select Name,ifIndex,NetLuid,InterfaceGuid,Status,MacAddress,MtuSize,InterfaceType,Hidden,HardwareInterface,ConnectorPresent,MediaType,PhysicalMediaType | Out-File -FilePath "$Folder/Get-NetAdapter_$ReproStep.log" -Append } catch {}
60 try { & netsh nlm query all $Folder/nlmquery_"$ReproStep".log } catch {}
61 try { Get-NetIPConfiguration -All -Detailed | Out-File -FilePath "$Folder/Get-NetIPConfiguration_$ReproStep.log" -Append } catch {}
62 try { Get-NetRoute | Out-File -FilePath "$Folder/Get-NetRoute_$ReproStep.log" -Append } catch {}
63 try { Get-NetFirewallHyperVVMCreator | Out-File -FilePath "$Folder/Get-NetFirewallHyperVVMCreator_$ReproStep.log" -Append } catch {}
64 try { Get-NetFirewallHyperVVMSetting -PolicyStore ActiveStore | Out-File -FilePath "$Folder/Get-NetFirewallHyperVVMSetting_ActiveStore_$ReproStep.log" -Append } catch {}
65 try { Get-NetFirewallHyperVProfile -PolicyStore ActiveStore | Out-File -FilePath "$Folder/Get-NetFirewallHyperVProfile_ActiveStore_$ReproStep.log" -Append } catch {}
66 try { Get-NetFirewallHyperVRule -PolicyStore ActiveStore | Out-File -FilePath "$Folder/Get-NetFirewallHyperVRule_ActiveStore_$ReproStep.log" -Append } catch {}
67 try { Get-NetFirewallRule -PolicyStore ActiveStore | Out-File -FilePath "$Folder/Get-NetFirewallRule_ActiveStore_$ReproStep.log" -Append } catch {}
68 try { Get-NetFirewallProfile -PolicyStore ActiveStore | Out-File -FilePath "$Folder/Get-NetFirewallProfile_ActiveStore_$ReproStep.log" -Append } catch {}
69 try { Get-NetFirewallHyperVPort | Out-File -FilePath "$Folder/Get-NetFirewallHyperVPort_$ReproStep.log" -Append } catch {}
70 try { & hnsdiag.exe list all 2>&1 > $Folder/hnsdiag_list_all_"$ReproStep".log } catch {}
71 try { & hnsdiag.exe list endpoints -df 2>&1 > $Folder/hnsdiag_list_endpoints_"$ReproStep".log } catch {}
72 try {
73 foreach ($port in Get-NetFirewallHyperVPort) {
74 & vfpctrl.exe /port $port.PortName /get-port-state 2>&1 > "$Folder/vfp-port-$($port.PortName)-get-port-state_$ReproStep.log"
75 & vfpctrl.exe /port $port.PortName /list-rule 2>&1 > "$Folder/vfp-port-$($port.PortName)-list-rule_$ReproStep.log"
76 }
77 } catch {}
78 try { & vfpctrl.exe /list-vmswitch-port 2>&1 > $Folder/vfpctrl_list_vmswitch_port_"$ReproStep".log } catch {}
79 try { Get-VMSwitch | select Name,Id,SwitchType | Out-File -FilePath "$Folder/Get-VMSwitch_$ReproStep.log" -Append } catch {}
80 try { Get-NetUdpEndpoint | Out-File -FilePath "$Folder/Get-NetUdpEndpoint_$ReproStep.log" -Append } catch {}
81 }
82
83 $folder = "WslLogs-" + (Get-Date -Format "yyyy-MM-dd_HH-mm-ss")
84 mkdir -p $folder | Out-Null
85
86 # Check if LogProfile is a custom file path or a profile name
87 if ($LogProfile -ne $null -And [System.IO.File]::Exists($LogProfile))
88 {
89 # User provided a custom .wprp file path - use it directly
90 $wprpFile = $LogProfile
91 $wprpProfile = $null # Use default profile in the file
92 }
93 else
94 {
95 # Map log profile names to WPRP profile names
96 $wprpProfile = "WSL"
97 if ($LogProfile -eq "storage")
98 {
99 $wprpProfile = "WSL-Storage"
100 }
101 elseif ($LogProfile -eq "networking")
102 {
103 $wprpProfile = "WSL-Networking"
104 }
105 elseif ($LogProfile -eq "hvsocket")
106 {
107 $wprpProfile = "WSL-HvSocket"
108 }
109 elseif ($LogProfile -ne $null)
110 {
111 Write-Error "Unknown log profile: $LogProfile. Valid options are: storage, networking, hvsocket, or a path to a custom .wprp file"
112 exit 1
113 }
114
115 # Use the consolidated wsl.wprp file, attempt to use local copy first.
116 $wprpFile = "$folder/wsl.wprp"
117 if (Test-Path "$PSScriptRoot/wsl.wprp")
118 {
119 Copy-Item "$PSScriptRoot/wsl.wprp" $wprpFile
120 }
121 else
122 {
123 Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/wsl.wprp" -OutFile $wprpFile
124 }
125 }
126
127 # Networking-specific setup
128 if ($LogProfile -eq "networking")
129 {
130 Test-WslApplication -Name "tcpdump" | Out-Null
131 Test-WslApplication -Name "iptables" | Out-Null
132
133 # Copy/download networking.sh script
134 $networkingBashScript = "$folder/networking.sh"
135 if (Test-Path "$PSScriptRoot/networking.sh")
136 {
137 Copy-Item "$PSScriptRoot/networking.sh" $networkingBashScript
138 }
139 else
140 {
141 Write-Host -ForegroundColor Yellow "networking.sh not found in the current directory. Downloading it from GitHub."
142 Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/networking.sh" -OutFile $networkingBashScript
143 }
144
145 # Detect the super user (uid=0, not necessarily named "root" - see #11693)
146 $superUser = & wsl.exe -- id -nu 0
147
148 # Collect Linux & Windows network state before the repro
149 & wsl.exe -u $superUser -e $networkingBashScript 2>&1 > $folder/linux_network_configuration_before.log
150 Collect-WindowsNetworkState -Folder $folder -ReproStep "before_repro"
151
152 if ($RestartWslReproMode)
153 {
154 # The WSL HNS network is created once per boot. Resetting it to collect network creation logs.
155 # Note: The below HNS command applies only to WSL in NAT mode
156 Get-HnsNetwork | Where-Object {$_.Name -eq 'WSL' -Or $_.Name -eq 'WSL (Hyper-V firewall)'} | Remove-HnsNetwork
157
158 # Stop WSL
159 net.exe stop WslService
160 if(-not $?) { net.exe stop LxssManager }
161 }
162 }
163
164 reg.exe export HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Lxss $folder/HKCU.txt 2>&1 | Out-Null
165 reg.exe export HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Lxss $folder/HKLM.txt 2>&1 | Out-Null
166 reg.exe export HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\P9NP $folder/P9NP.txt 2>&1 | Out-Null
167 reg.exe export HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WinSock2 $folder/Winsock2.txt 2>&1 | Out-Null
168 reg.exe export "HKEY_CLASSES_ROOT\CLSID\{e66b0f30-e7b4-4f8c-acfd-d100c46c6278}" $folder/wslsupport-proxy.txt 2>&1 | Out-Null
169 reg.exe export "HKEY_CLASSES_ROOT\CLSID\{a9b7a1b9-0671-405c-95f1-e0612cb4ce7e}" $folder/wslsupport-impl.txt 2>&1 | Out-Null
170 Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" > $folder/windows-version.txt
171
172 Get-Service wslservice -ErrorAction Ignore | Format-list * -Force > $folder/wslservice.txt
173
174 $wslconfig = "$env:USERPROFILE/.wslconfig"
175 if (Test-Path $wslconfig)
176 {
177 Copy-Item $wslconfig $folder | Out-Null
178 }
179
180 # Collect high-level WSL install log (written by WriteInstallLog() in install.cpp)
181 Copy-Item "C:\Windows\temp\wsl-install-log.txt" $folder -ErrorAction ignore
182
183 # Collect MSI verbose install log (preserved on failure by wsl --update or WslInstaller service).
184 Copy-Item "$env:TEMP\wsl-install-logs.txt" $folder -ErrorAction ignore
185
186 get-appxpackage MicrosoftCorporationII.WindowsSubsystemforLinux -ErrorAction Ignore > $folder/appxpackage.txt
187 get-acl "C:\ProgramData\Microsoft\Windows\WindowsApps" -ErrorAction Ignore | Format-List > $folder/acl.txt
188 Get-WindowsOptionalFeature -Online > $folder/optional-components.txt
189 bcdedit.exe > $folder/bcdedit.txt
190
191 $uninstallLogs = "$env:TEMP/wsl-uninstall-logs.txt"
192 if (Test-Path $uninstallLogs)
193 {
194 Copy-Item $uninstallLogs $folder | Out-Null
195 }
196
197 $wprOutputLog = "$folder/wpr.txt"
198
199 # Build wpr command - if wprpProfile is set, use profile syntax, otherwise use file only
200 if ($wprpProfile -ne $null)
201 {
202 $wprCommand = "$wprpFile!$wprpProfile"
203 }
204 else
205 {
206 $wprCommand = $wprpFile
207 }
208
209 wpr.exe -start $wprCommand -filemode 2>&1 >> $wprOutputLog
210 if ($LastExitCode -Ne 0)
211 {
212 Write-Host -ForegroundColor Yellow "Log collection failed to start (exit code: $LastExitCode), trying to reset it."
213 wpr.exe -cancel 2>&1 >> $wprOutputLog
214
215 wpr.exe -start $wprCommand -filemode 2>&1 >> $wprOutputLog
216 if ($LastExitCode -Ne 0)
217 {
218 Write-Host -ForegroundColor Red "Couldn't start log collection (exitCode: $LastExitCode)"
219 }
220 }
221
222 # Start networking-specific captures
223 $tcpdumpProcess = $null
224 if ($LogProfile -eq "networking")
225 {
226 pktmon start -c --flags 0x1A --file-name "$folder/pktmon.etl" | out-null
227 netsh wfp capture start file="$folder/wfpdiag.cab"
228
229 # Ensure WSL is running before collecting network state
230 & wsl.exe -- true 2>&1 | Out-Null
231
232 # Start tcpdump (may not be installed)
233 try
234 {
235 $tcpdumpProcess = Start-Process wsl.exe -ArgumentList "-u $superUser tcpdump -n -i any -e -vvv > $folder/tcpdump.log" -WindowStyle Hidden -PassThru
236 }
237 catch {}
238 }
239
240 try
241 {
242 Write-Host -NoNewLine "Log collection is running. Please "
243 Write-Host -NoNewLine -ForegroundColor Red "reproduce the problem "
244 Write-Host -NoNewLine "and once done press any key to save the logs."
245
246 $KeysToIgnore =
247 16, # Shift (left or right)
248 17, # Ctrl (left or right)
249 18, # Alt (left or right)
250 20, # Caps lock
251 91, # Windows key (left)
252 92, # Windows key (right)
253 93, # Menu key
254 144, # Num lock
255 145, # Scroll lock
256 166, # Back
257 167, # Forward
258 168, # Refresh
259 169, # Stop
260 170, # Search
261 171, # Favorites
262 172, # Start/Home
263 173, # Mute
264 174, # Volume Down
265 175, # Volume Up
266 176, # Next Track
267 177, # Previous Track
268 178, # Stop Media
269 179, # Play
270 180, # Mail
271 181, # Select Media
272 182, # Application 1
273 183 # Application 2
274
275 $Key = $null
276 while ($Key -Eq $null -Or $Key.VirtualKeyCode -Eq $null -Or $KeysToIgnore -Contains $Key.VirtualKeyCode)
277 {
278 $Key = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
279 }
280
281 Write-Host "`nSaving logs..."
282 }
283 finally
284 {
285 # Stop networking-specific captures
286 if ($LogProfile -eq "networking")
287 {
288 try
289 {
290 wsl.exe -u $superUser killall tcpdump
291 if ($tcpdumpProcess -ne $null)
292 {
293 Wait-Process -InputObject $tcpdumpProcess -Timeout 10
294 }
295 }
296 catch {}
297
298 netsh wfp capture stop
299 pktmon stop | out-null
300 }
301
302 wpr.exe -stop $folder/logs.etl 2>&1 >> $wprOutputLog
303 }
304
305 # Networking-specific post-repro collection
306 if ($LogProfile -eq "networking")
307 {
308 # Collect Linux & Windows network state after the repro
309 & wsl.exe -u $superUser -e $networkingBashScript 2>&1 > $folder/linux_network_configuration_after.log
310 Collect-WindowsNetworkState -Folder $folder -ReproStep "after_repro"
311
312 try
313 {
314 # Collect HNS events from past 24 hours
315 $events = Get-WinEvent -ProviderName Microsoft-Windows-Host-Network-Service | Where-Object { $_.TimeCreated -ge ((Get-Date) - (New-TimeSpan -Day 1)) }
316 ($events | ForEach-Object { '{0},{1},{2},{3}' -f $_.TimeCreated, $_.Id, $_.LevelDisplayName, $_.Message }) -join [environment]::NewLine | Out-File -FilePath "$folder/hns_events.log" -Append
317 }
318 catch {}
319
320 # Collect the old Tcpip6 registry values - as they can break WSL if DisabledComponents is set to 0xff
321 # see https://learn.microsoft.com/en-us/troubleshoot/windows-server/networking/configure-ipv6-in-windows
322 try
323 {
324 Get-Item HKLM:SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters | Out-File -FilePath "$folder/tcpip6_parameters.log" -Append
325 }
326 catch {}
327
328 # Collect the setup and NetSetup log files
329 $netSetupPath = "$env:WINDIR/logs/netsetup"
330 if (Test-Path $netSetupPath)
331 {
332 Copy-Item $netSetupPath/* $folder
333 }
334
335 $setupApiPath = "$env:WINDIR/inf/setupapi.dev.log"
336 if (Test-Path $setupApiPath)
337 {
338 Copy-Item $setupApiPath $folder
339 }
340
341 Remove-Item $networkingBashScript
342 }
343
344 # Collect WSLg logs (https://github.com/microsoft/wslg)
345 $wslgFolder = "$folder/wslg"
346 New-Item -ItemType Directory -Force -Path $wslgFolder | Out-Null
347
348 # Run in a job with a timeout so a wedged WSL service can't hang collection. --system --user root
349 # reaches /mnt/wslg even when the default distro is WSL1 or isn't running, and can read root-only logs.
350 $wslgJob = Start-Job -ScriptBlock {
351 param($DestFull, $CollectDumps)
352
353 $destWsl = "$(& wsl.exe --system --user root -e wslpath -u "$DestFull" 2>$null)".Trim()
354 if ([string]::IsNullOrWhiteSpace($destWsl)) { return }
355
356 # Destination is passed as $1 so paths containing a single quote are handled safely. In
357 # `sh -c '<script>' sh <arg>`, the token after the script becomes $0 (here "sh") and the
358 # next becomes $1 (the destination path).
359 & wsl.exe --system --user root -e sh -c 'cp /mnt/wslg/pulseaudio.log /mnt/wslg/weston.log /mnt/wslg/wlog.log /mnt/wslg/stderr.log /mnt/wslg/versions.txt "$1/" 2>/dev/null; exit 0' sh "$destWsl"
360
361 if ($CollectDumps)
362 {
363 & wsl.exe --system --user root -e sh -c '[ -d /mnt/wslg/dumps ] && cp -r /mnt/wslg/dumps "$1/dumps"; exit 0' sh "$destWsl"
364 }
365 } -ArgumentList (Resolve-Path $wslgFolder).Path, ([bool]$Dump)
366
367 if (Wait-Job $wslgJob -Timeout 20)
368 {
369 Receive-Job $wslgJob | Out-Null
370 }
371 else
372 {
373 Write-Host -ForegroundColor Yellow "WSLg log collection timed out and was skipped."
374 Stop-Job $wslgJob
375 }
376 Remove-Job $wslgJob -Force
377
378 # Crash dumps are only collected with -Dump, since users may not expect dumps to be published by default.
379 if ($Dump)
380 {
381 $wslCrashes = "$env:TEMP\wsl-crashes"
382 if (Test-Path $wslCrashes)
383 {
384 Copy-Item $wslCrashes "$wslgFolder/wsl-crashes" -Recurse -ErrorAction Ignore
385 }
386 }
387
388 if ($Dump)
389 {
390 $Assembly = [PSObject].Assembly.GetType('System.Management.Automation.WindowsErrorReporting')
391 $DumpMethod = $Assembly.GetNestedType('NativeMethods', 'NonPublic').GetMethod('MiniDumpWriteDump', [Reflection.BindingFlags] 'NonPublic, Static')
392
393 $dumpFolder = Join-Path (Resolve-Path "$folder") dumps
394 New-Item -ItemType "directory" -Path "$dumpFolder"
395
396 $executables = "wsl", "wslservice", "wslhost", "wslcsession", "wslrelay", "wslg", "msrdc", "dllhost"
397 foreach($process in Get-Process | Where-Object { $executables -contains $_.ProcessName})
398 {
399 $dumpFile = "$dumpFolder/$($process.ProcessName).$($process.Id).dmp"
400 Write-Host "Writing $($dumpFile)"
401
402 $OutputFile = New-Object IO.FileStream($dumpFile, [IO.FileMode]::Create)
403
404 $Result = $DumpMethod.Invoke($null, @($process.Handle,
405 $process.id,
406 $OutputFile.SafeFileHandle,
407 [UInt32] 2,
408 [IntPtr]::Zero,
409 [IntPtr]::Zero,
410 [IntPtr]::Zero))
411
412 $OutputFile.Close()
413 if (-not $Result)
414 {
415 Write-Host "Failed to write dump for: $($dumpFile)"
416 }
417 }
418 }
419
420 $logArchive = "$(Resolve-Path $folder).tar.gz"
421 tar.exe -czf $logArchive $folder
422 if ($LASTEXITCODE -eq 0)
423 {
424 Remove-Item $folder -Recurse
425 Write-Host -ForegroundColor Green "Logs saved in: $logArchive. Please attach that file to the GitHub issue."
426 }
427 else
428 {
429 Remove-Item $logArchive -ErrorAction Ignore
430
431 # Fall back to zip if tar fails (e.g. on SKUs that lack tar.exe)
432 $logArchive = "$(Resolve-Path $folder).zip"
433 try
434 {
435 Compress-Archive -Path $folder -DestinationPath $logArchive -Force
436 Remove-Item $folder -Recurse
437 Write-Host -ForegroundColor Green "Logs saved in: $logArchive. Please attach that file to the GitHub issue."
438 }
439 catch
440 {
441 Remove-Item $logArchive -ErrorAction Ignore
442 Write-Host -ForegroundColor Red "Failed to compress logs. They are available in: $(Resolve-Path $folder)"
443 }
444 }