Enable-PSTrace: Tracing Your Way Through PowerShell
Welcome back to Wahmans PowerShell Blog!
Today, we’re diving into the Enable-PSTrace cmdlet. As described by Microsoft, this cmdlet “Enables the Microsoft-Windows-PowerShell event provider logs.” But what does that actually mean—and why should you care?
Enable-PSTrace is a diagnostic tool that lets you trace what’s happening inside PowerShell by enabling specific ETW (Event Tracing for Windows) providers. This is particularly useful when troubleshooting issues or understanding PowerShell internals. Once enabled, logs are sent to the Windows Event Log under the “Microsoft-Windows-PowerShell/Operational” log channel.
Getting Started with Enable-PSTrace
Let’s walk through four examples of how you can use Enable-PSTrace, progressing from beginner to more advanced usage.
Example 1: Enabling PowerShell Trace Logging (Basic)
This will enable PowerShell trace logging. It’s the simplest way to start gathering diagnostic data:
Enable-PSTrace
That’s it! Now you can open the Event Viewer and navigate to Applications and Services Logs → Microsoft → Windows → PowerShell → Operational to see logs as PowerShell operates.
Example 2: Pairing with Get-WinEvent for Real-Time Logging
To view events as they’re logged, you can use Get-WinEvent like so:
Enable-PSTrace
Get-WinEvent -LogName 'Microsoft-Windows-PowerShell/Operational' | Select-Object -First 10
This allows you to get the top 10 recent PowerShell operational events after enabling the trace.
Example 3: Logging Script Failures in Production
If you’re running PowerShell scripts in production and want to log failures to the Operational log for later analysis, enable tracing and then execute your scripts:
Enable-PSTrace
try {
# Simulated command that fails
Get-Item "C:\NonExistentFile.txt"
} catch {
Write-Error "An error occurred. Check event logs for details."
}
Now head over to the Operational event logs to view details of the command failure.
Example 4: Advanced Debugging with ETW and Logman
If you’re doing advanced diagnostics, you could pair Enable-PSTrace with ETW tooling like logman to capture logs to a file:
Enable-PSTrace
logman start PS_Trace -p Microsoft-Windows-PowerShell -o C:\Logs\PSTrace.etl
This command tells Windows to log all PowerShell ETW events to an ETL (Event Trace Log) file, which can later be analyzed with tools like Windows Performance Analyzer or Message Analyzer.
Wrapping Up
Enable-PSTrace is a powerful, underutilized cmdlet in your toolbelt, especially when things start going sideways. Whether you’re troubleshooting scripts, understanding PowerShell’s inner workings, or building production-ready diagnostics, it’s worth knowing how to trace your steps!
Happy scripting, and I will see you in the next post!
Leave a Reply