21

我试图在运行 PowerShell 脚本时获取错误的行号。这是我目前正在使用的:

$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

有时这有效,有时无效。我想知道我是否做错了什么,或者我能做些什么来使这项工作更加一致。

4

2 回答 2

37

我弄清楚了问题所在:

代替:

$e = $_.Exception
#this is wrong
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

它应该是

$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"
于 2013-06-21T02:45:34.510 回答
13

这是捕获详细异常的另一种有用方法

try
{
    throw "fdsfds"
}
catch
{
    Write-Error ($_.Exception | Format-List -Force | Out-String) -ErrorAction Continue
    Write-Error ($_.InvocationInfo | Format-List -Force | Out-String) -ErrorAction Continue
    throw
}
于 2018-08-24T08:30:16.370 回答