Powershell:如何从写入错误中获取完整的堆栈跟踪

问题描述 投票:0回答:1

如何获取

Write-Error
消息的完整堆栈跟踪?

例如以下代码

function a {
    write-error "error"
}

function b {
    a
}

function c {
    b
}

c

仅输出最后一个堆栈帧:

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
powershell error-handling
1个回答
0
投票

检查关联错误记录上的

ScriptStackTrace
属性:

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
}

在 PowerShell 7 中,您还可以配置

DetailedView
$ErrorView
首选项以默认在错误输出中显示脚本堆栈跟踪:

$ErrorView = 'DetailedView'
© www.soinside.com 2019 - 2024. All rights reserved.