2

给定脚本。

$foo = @("bar")

try {
    $foo | ForEach-Object {
        Join-Path $null $null
    }
} catch {
    $_.InvocationInfo.Line
}

将打印

$foo | ForEach-Object {

但我想

Join-Path $null $null

我怎样才能得到实际引发异常的位置?

4

1 回答 1

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
}
于 2012-05-11T21:21:55.027 回答