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



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

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

是否可以包含变量名称、行号或任何可以帮助我找到错误位置的信息?例如,在powershell终端中运行的代码会显示相应的行。

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

关于检测和处理脚本错误,已经在SO上写了很多文章,关于Trap和Try-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:Templogfiletest.txt" -Value $_,$_.InvocationInfo.PositionMessage
return   
}
# Div/0 triggers the trap to test behaviour    
1/0

陷阱本身(或类似的东西(应该能捕捉到你所碰到的错误。尽管在实践中(不知道你多久运行一次,也不知道你产生了多少错误(,你还是要小心,不要无意中在C:上产生过大的日志文件。你可以通过选择风险较低的驱动器/位置并在文件名中放入动态日期来避免这种情况。

最新更新