Can I get detailed exception stacktrace in PowerShell?

前端 未结 12 1148
暗喜
暗喜 2020-12-02 12:23

Runing such script:

 1: function foo()
 2: {
 3:    bar
 4: }
 5: 
 6: function bar()
 7: {
 8:     throw \"test\"
 9: }
10: 
11: foo

I see

12条回答
  •  醉话见心
    2020-12-02 12:49

    Powershell 3.0 adds a ScriptStackTrace property to the ErrorRecord object. I use this function for error reporting:

    function Write-Callstack([System.Management.Automation.ErrorRecord]$ErrorRecord=$null, [int]$Skip=1)
    {
        Write-Host # blank line
        if ($ErrorRecord)
        {
            Write-Host -ForegroundColor Red "$ErrorRecord $($ErrorRecord.InvocationInfo.PositionMessage)"
    
            if ($ErrorRecord.Exception)
            {
                Write-Host -ForegroundColor Red $ErrorRecord.Exception
            }
    
            if ((Get-Member -InputObject $ErrorRecord -Name ScriptStackTrace) -ne $null)
            {
                #PS 3.0 has a stack trace on the ErrorRecord; if we have it, use it & skip the manual stack trace below
                Write-Host -ForegroundColor Red $ErrorRecord.ScriptStackTrace
                return
            }
        }
    
        Get-PSCallStack | Select -Skip $Skip | % {
            Write-Host -ForegroundColor Yellow -NoNewLine "! "
            Write-Host -ForegroundColor Red $_.Command $_.Location $(if ($_.Arguments.Length -le 80) { $_.Arguments })
        }
    }
    

    The Skip parameter lets me leave Write-Callstack or any number of error-handling stack frames out of the Get-PSCallstack listing.

    Note that if called from a catch block, Get-PSCallstack will miss any frames between the throw site and the catch block. Hence I prefer the PS 3.0 method even though we have fewer details per frame.

提交回复
热议问题