sql - Powershell 使用 ExecuteNonQuery() 尝试 Catch

标签 sql powershell error-handling runtime-error

我正在研究一个将跨多个服务器执行脚本的 powershell 脚本。
使用 http://ps2exe.codeplex.com/ 将我的脚本转换为 exe 后
当我关闭窗口时,如果在 try catch 中发现任何错误,我会收到错误消息。

$ErrorActionPreference = 'Continue'
    $dataAdapter = new-object System.Data.SqlClient.SqlCommand ($ExeStatement, $connString);
    $dataAdapter.Connection.Open();
    $dataAdapter.CommandTimeout = 65535;
    Try {
        $dataAdapter.ExecuteNonQuery()}
    catch{
         $ErrorCounter = $ErrorCounter + 1
         $dataAdapter.Connection.Close();}
    finally{
         $dataAdapter.Connection.Close();}
如果我删除了 try catch,我可以在捕获到错误时很好地关闭窗口。
如果我删除 $dataAdapter.CommandTimeout = 65535;当发现错误时,我可以很好地关闭窗口,但我需要这个,因为其中一个脚本相当长。
如果我将 ErrorActionPreference 设置为 STOP 它也可以正常工作。虽然我希望能够继续解决错误并在最后报告。
关闭窗口时,我从窗口收到以下错误。

Description: Stopped working

Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01: PROGRAMNAME.exe
Problem Signature 02: 0.0.0.0
Problem Signature 03: 53bdc0d9
Problem Signature 04: mscorlib
Problem Signature 05: 2.0.0.0
Problem Signature 06: 5174de33
Problem Signature 07: 34a9
Problem Signature 08: 18c
Problem Signature 09: System.IO.IOException
OS Version: 6.1.7601.2.1.0.16.7
Locale ID: 1033
DefaultDataCollection failed: 0x8007001f


我需要脚本能够继续处理错误,但我还需要捕获错误。

最佳答案

我猜 OP 已经解决了这个问题,但是对于任何偶然发现它的人来说,可能的解决方法是他在捕获错误时尝试关闭数据适配器两次:一次在 catch block 中,一次在 finally block 中,但是它已经在 catch block 中关闭。
OP 指出,这只发生在他有错误时。是的,因为这是导致双重收盘的唯一条件。
简单的答案是从 catch block 中移除数据适配器 close 并让 finally block 处理它。

关于sql - Powershell 使用 ExecuteNonQuery() 尝试 Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681938/

相关文章:

c# - MySqlCommand.LastInsertedId 是如何工作的?

mysql - 使用 IN 语句进行缓慢的 mysql 删除查询

powershell - 为什么是Get-DnsClientServerAddress |选择AddressFamily输出不是IPv4和IPv6

powershell - 在安装在 Mac 上的 VSTS 代理中运行 powershell 构建步骤?

error-handling - Dreamweaver CS5-看看PHP中有什么错误?

mysql - 从每日最低值中选择数据

sql - 动态创建表来存储用户内容是个好主意吗?

azure - PowerShell 或 Azure CLI - 显示/创建已设置 PIM 的 Azure 安全组

javascript - 为什么 React JS 中的错误边界不起作用

angularjs - AngularJS和ExpressJS HTTP错误处理