如何在Powershell中获取错误行号

时间:2013-06-21 02:13:08

标签: windows powershell

我正在尝试在运行Powershell脚本时获取错误的行号。以下是我目前正在使用的内容:

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

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

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

2 个答案:

答案 0 :(得分:20)

我弄清楚问题是什么:

而不是:

$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"

答案 1 :(得分:0)

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

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 }