使用 PowerShell 命令行时未捕获异常,但使用 PowerShell ISE 时按预期捕获异常 [英] Exception not caught when using PowerShell command line but caught as expected when using PowerShell ISE

查看:58
本文介绍了使用 PowerShell 命令行时未捕获异常,但使用 PowerShell ISE 时按预期捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行 PowerShell 2.0.

I am running PowerShell 2.0.

我有一个 PowerShell 脚本,可以将记录添加到数据库并返回添加的记录的 ID.记录 ID 作为 DataRow 对象(称为 ResultSet)中名为 new_deal_id 的属性返回.

I have a PowerShell script that adds a record to the database and returns the ID of the record added. The record ID is returned as a property called new_deal_id within a DataRow object (called ResultSet).

如果数据库端出现问题,可能是 new_deal_id 属性没有设置,或者根本不存在.

If there is a problem on the database end it is possible that the new_deal_id property does not get set, or doesn't exist at all.

为了应对这种情况,我将属性的读取包装在一个 try/catch 块中,如下所示.

To counter this scenario I wrapped the reading of the property in a try/catch block as shown here.

try {
    $ErrorActionPreference = "Stop"
    $ResultSet = Read-DatabaseData -OdbcCommand $OdbcCommand -SqlQuery $Sql
    $NewDealID = $ResultSet.new_deal_id
}
catch {
    throw
}
finally {
    $ErrorActionPreference = "Continue"
}

如果我使用 PowerShell ISE 或 PowerGui 运行脚本,则会在该属性不存在时捕获下面显示的异常

If I run the script using the PowerShell ISE or PowerGui the exception shown below gets caught when the property doesn't exist

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 命令行运行脚本,则不会捕获异常,脚本会继续运行,就像没有发生错误一样.

However if I run the script from the PowerShell command line the exception does not get caught and the script continues as if no error occurred.

当属性不存在时,为什么 PowerShell 命令行没有捕获异常?

Why is the PowerShell command line not catching the exception when the property doesn't exist?

推荐答案

这可能是因为您在运行脚本的控制台中没有启用严格模式.(Powershell 和 ISE 使用不同的配置文件)

This is probably because you dont have strict mode enabled in the console you are running your script in. (Powershell and ISE use different profiles)

要启用严格模式,请使用 Set-Strictmode cmdlet.

To enable strict mode use the Set-Strictmode cmdlet.

示例:

Set-StrictMode -Version latest

这篇关于使用 PowerShell 命令行时未捕获异常,但使用 PowerShell ISE 时按预期捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆