给出了剧本。
$foo = @("bar")
try {
$foo | ForEach-Object {
Join-Path $null $null
}
} catch {
$_.InvocationInfo.Line
}
将打印
$foo | ForEach-Object {
但我想
Join-Path $null $null
如何才能获得实际引发异常的位置?
答案 0 :(得分:4)
这将为您提供实际的一行:
$_.Exception.CommandInvocation.Line
和异常消息:
$_.Exception.Message
和行号:
$_.Exception.Line
和偏移(列):
$_.Exception.Offset
所以你可以发一个有用的小信息:
} catch {
$msg = "Failed to do something. Failed on line number '{0}' column '{1}' ('{2}'). The error was '{3}'." -f
$_.Exception.Line, $_.Exception.Offset, $_.Exception.CommandInvocation.Line.Trim(), $_.Exception.Message
Write-Error $msg
}