如何在Powershell中获取错误行号

Bla*_*rai 16 windows powershell

我正在尝试在运行Powershell脚本时获取错误的行号.这是我现在正在使用的内容:

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

Write-Host -ForegroundColor Red "caught exception: $e at $line"
Run Code Online (Sandbox Code Playgroud)

有时候这种方法有效,有时则无效.我想知道我做错了什么,或者我能做些什么来使这项工作更加一致.

Bla*_*rai 26

我弄清楚问题是什么:

代替:

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

Write-Host -ForegroundColor Red "caught exception: $e at $line"
Run Code Online (Sandbox Code Playgroud)

它应该是

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

Write-Host -ForegroundColor Red "caught exception: $e at $line"
Run Code Online (Sandbox Code Playgroud)


小智 11

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

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
}
Run Code Online (Sandbox Code Playgroud)