此代码按预期工作:
function Foo ($Dividend) {
$Divisor = 0
$Quotient = $Dividend / $Divisor
}
try {
Foo 1
} catch {
$Line = $($_.InvocationInfo.Line).Trim()
$Row = $($_.InvocationInfo.ScriptLineNumber)
$Col = $($_.InvocationInfo.OffsetInLine)
Write-Host "Error: $_" -ForegroundColor "Red"
Write-Host " -> Row: $Row" -ForegroundColor "Red"
Write-Host " -> Col: $Col" -ForegroundColor "Red"
Write-Host " -> Line: $Line" -ForegroundColor "Red"
}
打印此文字:
Error: Attempted to divide by zero. -> Row: 3 -> Col: 5 -> Line: $Quotient = $Dividend / $Divisor
然而这失败了:
function Foo ($Dividend) {
$Divisor = 0
$Quotient = $Dividend / $Divisor
}
try {
$Dividends = @(1)
$Dividends | ForEach {
Foo $_
}
} catch {
$Line = $($_.InvocationInfo.Line).Trim()
$Row = $($_.InvocationInfo.ScriptLineNumber)
$Col = $($_.InvocationInfo.OffsetInLine)
Write-Host "Error: $_" -ForegroundColor "Red"
Write-Host " -> Row: $Row" -ForegroundColor "Red"
Write-Host " -> Col: $Col" -ForegroundColor "Red"
Write-Host " -> Line: $Line" -ForegroundColor "Red"
}
打印出来:
Error: Attempted to divide by zero. -> Row: 11 -> Col: 22 -> Line: $Dividends | ForEach {
在ForEach
循环中调用函数时,有没有办法获取正确范围的错误信息?
答案 0 :(得分:0)
您要查找的信息嵌套在顶级} catch {
$Line = $($_.InvocationInfo.Line).Trim()
$Row = $($_.InvocationInfo.ScriptLineNumber)
$Col = $($_.InvocationInfo.OffsetInLine)
Write-Host "Error: $_" -ForegroundColor "Red"
Write-Host " -> Row: $Row" -ForegroundColor "Red"
Write-Host " -> Col: $Col" -ForegroundColor "Red"
Write-Host " -> Line: $Line" -ForegroundColor "Red"
}
对象中。您需要展开错误对象以获取嵌套信息。
改变这个:
} catch {
$Line = $($_.Exception.ErrorRecord.InvocationInfo.Line).Trim()
$Row = $($_.Exception.ErrorRecord.InvocationInfo.ScriptLineNumber)
$Col = $($_.Exception.ErrorRecord.InvocationInfo.OffsetInLine)
Write-Host "Error: $_" -ForegroundColor "Red"
Write-Host " -> Row: $Row" -ForegroundColor "Red"
Write-Host " -> Col: $Col" -ForegroundColor "Red"
Write-Host " -> Line: $Line" -ForegroundColor "Red"
}
进入这个:
LOCAL_JACK_ENABLED := incremental
并且代码应该按照您的预期运行。