我正在尝试在运行Powershell脚本时获取错误的行号。以下是我目前正在使用的内容:
$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
有时这种方法有效,有时则无效。我想知道我做错了什么,或者我能做些什么来使这项工作更加一致。
答案 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
}