提问人:gerard 提问时间:11/11/2014 更新时间:11/12/2014 访问量:1122
使用 PowerShell 命令行时未捕获异常,但在使用 PowerShell ISE 时按预期捕获异常
Exception not caught when using PowerShell command line but caught as expected when using PowerShell ISE
问:
我正在运行 PowerShell 2.0。
我有一个 PowerShell 脚本,该脚本将记录添加到数据库并返回所添加记录的 ID。
记录 ID 作为在 DataRow 对象中调用的属性返回(称为 )。new_deal_id
ResultSet
如果数据库端出现问题,则该属性可能未设置,或者根本不存在。new_deal_id
为了应对这种情况,我将属性的读取包装在一个 try/catch 块中,如下所示。
try {
$ErrorActionPreference = "Stop"
$ResultSet = Read-DatabaseData -OdbcCommand $OdbcCommand -SqlQuery $Sql
$NewDealID = $ResultSet.new_deal_id
}
catch {
throw
}
finally {
$ErrorActionPreference = "Continue"
}
如果我使用 PowerShell ISE 或 PowerGui 运行脚本,则当属性不存在时,会捕获如下所示的异常
Property 'new_deal_id' cannot be found on this object. Make sure that it exists.
At line:1 char:12
+ $ResultSet. <<<< newdeal
+ CategoryInfo : InvalidOperation: (.:OperatorToken) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
但是,如果我从 PowerShell 命令行运行脚本,则不会捕获异常,并且脚本会继续,就好像没有发生错误一样。
当属性不存在时,为什么 PowerShell 命令行不会捕获异常?
答:
1赞
Paul
11/12/2014
#1
这可能是因为您没有在运行脚本的控制台中启用严格模式。(Powershell 和 ISE 使用不同的配置文件)
若要启用严格模式,请使用 cmdlet。Set-Strictmode
例:
Set-StrictMode -Version latest
评论
0赞
gerard
11/12/2014
严格模式在主脚本中设置,但不会传递给单独模块中的函数。正如 Paul 所建议的:完整的解决方案是在测试属性是否存在之前,在函数中再次设置严格模式。
评论
set-strictmode
get-member
-ErrorAction Stop
Set-StrictMode -Version latest
-ErrorAction Stop