Search code examples
powershellerror-handling

Powershell: how to get full stack trace from Write-Error


How do I get a full stack trace for Write-Error messages?

E.g. the following code

function a {
    write-error "error"
}

function b {
    a
}

function c {
    b
}

c

Outputs only last stack frame:

PS C:\> .\_test.ps1
a : error
At C:\_test.ps1:6 char:5
+     a
+     ~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,a

Solution

  • Inspect the ScriptStackTrace property on the associated error record:

    function a {
        write-error "error"
    }
    
    function b {
        a
    }
    
    function c {
        b
    }
    
    $ErrorActionPreference = 'Stop'
    
    try {
        c
    }
    catch {
        Write-Host "Encountered error. Script stack trace:"
        Write-Host $_.ScriptStackTrace
    }
    

    In PowerShell 7 you can also configure the DetailedView $ErrorView preference to show the script stack trace in error output by default:

    $ErrorView = 'DetailedView'