Trace Command - PowerShell


Trace-Command is a PowerShell command that enables tracing and debugging of other PowerShell commands and scripts. It allows you to track the execution flow, identify potential issues, and troubleshoot complex scenarios.


Trace-Command [-PSCommand] <ScriptBlock> [-TraceLevel <TraceLevel>] [-PassThru] [-Force] [-PSHost] [-DebugContext <Int32>] [-TraceSource <String>]


-PSCommand: Specifies the script block or command to trace.
-TraceLevel: Sets the tracing level. Default: Verbose.

  • Verbose: Displays all traced events.
  • Warning: Displays only warning and error events.
  • Error: Displays only error events.
    -PassThru: Passes the traced command output to the pipeline.
    -Force: Traces commands that would otherwise be skipped.
    -PSHost: Traces PowerShell host events.
    -DebugContext: Specifies the depth of the call stack to trace.
    -TraceSource: Sets the name of the tracing source.


Simple tracing:

Trace-Command { Get-Process }

Advanced tracing with multiple trace levels:

Trace-Command {
    Get-Process | ForEach-Object {
        Trace-Command { Get-Command -Name $_.Name } -TraceLevel Warning
} -TraceLevel Error

Common Issues

  • Performance impact: Tracing can slow down the execution of traced commands. Use with caution in performance-critical scenarios.
  • Too much output: High trace levels can generate大量的 verbose output. Use -TraceLevel Warning or -TraceLevel Error to reduce the volume of output.


With other PowerShell commands:

Get-Command -Name Get-Process | Trace-Command | Get-TraceData

To debug PowerShell scripts:

Import-Module MyScript.psm1
Trace-Command { Invoke-Command -ScriptBlock { Import-Module ./MyScript.psm1; MyFunction } }