如何从ForEach循环内部调用的函数中获取PowerShell错误详细信息

时间:2016-08-30 05:07:50

标签: powershell

此代码按预期工作:

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循环中调用函数时,有没有办法获取正确范围的错误信息?

1 个答案:

答案 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

并且代码应该按照您的预期运行。