Exception not caught when using PowerShell command line but caught as expected when using PowerShell ISE

大憨熊 提交于 2021-01-28 05:00:02

问题


I am running PowerShell 2.0.

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).

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.

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"
}

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

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.

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


回答1:


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)

To enable strict mode use the Set-Strictmode cmdlet.

Example:

Set-StrictMode -Version latest


来源:https://stackoverflow.com/questions/26849716/exception-not-caught-when-using-powershell-command-line-but-caught-as-expected-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!