获取 PowerShell 脚本中的错误位置 (System.Management.Automation)

时间:2021-07-14 09:26:30

标签: powershell .net-core

我有一个在 c# 服务 (System.Management.Automation) 中运行的 powershell 脚本。有时我很少收到以下错误:

Unable to cast object of type 'System.Double' to type 'System.String'.

是否可以以某种方式包含变量名称、行号或任何可以帮助我找到错误位置的内容?例如。在 powershell 终端中运行的代码向我显示了相应的行。

1 个答案:

答案 0 :(得分:1)

值得考虑您的错误处理和错误记录方法以避免此类问题。考虑您希望错误是终止性的还是非终止性的,以及是要抑制还是记录错误。

Much has already been written on SO 关于检测和处理脚本错误,还有关于 TrapTry-Catch-Finally 的大量 MS 文档,所以我不想讨论这个问题。

根据脚本从哪里运行以及使用什么凭据,一种技巧是将错误记录到日志文件中,您可以在这些错误发生时进行检查:

# Create C:\Temp directory if it doesn't exist
New-Item "C:\Temp" -Force -ItemType Directory | Out-Null

# Simple trap to catch all errors
trap {
    # This is a single-line output more suitable for on-screen error messages
    Write-Output "Error encountered: $_ $($_.InvocationInfo.PositionMessage.Split("`n")[0])"

    # This is a multi-line output to make it easier to find the error location in a file
    Add-Content -LiteralPath "C:\Temp\logfiletest.txt" -Value $_,$_.InvocationInfo.PositionMessage

    return   
}

# Div/0 triggers the trap to test behaviour    
1/0

单独的陷阱(或类似的东西)应该可以捕获您遇到的错误。尽管在实践中(不知道您运行它的频率或生成多少错误),您要小心不要无意中开始在 C 上生成过大的日志文件:-您可以通过选择一个风险较低的文件来避免这种情况驱动器/位置并将动态日期放入文件名中。