如何获取此示例中引发异常的行号?下面的例子只给出了我调用脚本块的行号(即$ sb.Invoke())。我想要我在“FooBar中出错”的行号。
function Foobar {
throw "Error in FooBar"
}
function Bar {
FooBar
}
function Foo {
Bar
}
try {
$sb = ${function:Foo}
$sb.Invoke()
}
catch {
$ErrorMessage = $_.Exception.Message
$line = $_.InvocationInfo.ScriptLineNumber
$script_name = $_.InvocationInfo.ScriptName
write-host "<--Error: Occurred on line $line in script $script_name."
Write-host "<--Error: $ErrorMessage"
}
更新:
如果我改变:
$sb = ${function:Foo}
$sb.Invoke()
到此:
$func_info = get-command Foo
Invoke-Command $func_info.ScriptBlock
它有效。
答案 0 :(得分:0)
这似乎是Invoke()的错误处理的限制 - 它传递错误消息但丢弃了调用信息。
一种解决方法是捕获并重新抛出scriptblock本身,但有更多信息,例如
$sb = {
try {
Foo
}
catch {
throw "Error: $($_.Exception.Message). Stack trace:`n$($_.ScriptStackTrace)"
}
}
$sb.Invoke()
输出:
<--Error: Occurred on line 22 in script .
<--Error: Exception calling "Invoke" with "0" argument(s): "Error: Error in FooBar. Stack trace:
at Foobar, <No file>: line 2
at Bar, <No file>: line 6
at Foo, <No file>: line 10
at <ScriptBlock>, <No file>: line 16
at <ScriptBlock>, <No file>: line 22"