【问题标题】:How to get the line number of error in PowerShell如何在PowerShell中获取错误行号
【发布时间】:2020-06-05 21:14:05
【问题描述】:

我试图在运行 PowerShell 脚本时获取错误的行号。这是我目前正在使用的:

$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

有时这有效,有时无效。我想知道我是否做错了什么,或者我可以做些什么来使这项工作更加一致。

【问题讨论】:

  • try catch 语句是否没有为您提供所需的信息?这是一个陷阱吗?
  • 不,try/catch 只会给出错误。它没有列出行号和内容。
  • 我猜想(虽然现在没有要捕获的异常)类似:catch {[Exception] $_.ScriptLineNumber } 可能会这样做...但我也只是捕获我的错误并回显异常并它通常给了我我需要的东西。所以我很高兴你找到它。
  • 我错了,我使用的是 try/catch。这段代码在 catch 语句中。

标签: windows powershell


【解决方案1】:

我发现了问题所在:

代替:

$e = $_.Exception
#this is wrong
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

应该是

$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

【讨论】:

  • 我认为阿布的回答更可取,甚至只是Write-Error $_.Exception.Message
【解决方案2】:

这是捕获详细异常的另一种有用方法

try
{
    throw "fdsfds"
}
catch
{
    Write-Error ($_.Exception | Format-List -Force | Out-String) -ErrorAction Continue
    Write-Error ($_.InvocationInfo | Format-List -Force | Out-String) -ErrorAction Continue
    throw
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多