如何在PowerShell中捕获SQL查询错误

发布于 2025-01-30 03:04:33 字数 559 浏览 4 评论 0原文

我在powershell脚本中有这样的查询,

try{
    $Query = "SELECT ID / 0 FROM Tables1"
    Invoke-Sqlcmd -Query $Query -ServerInstance $Global:Server -Database $Global:Database
}
catch {
    "error when running sql $Query "
    $error=  $_
}

我遇到的问题是,当我在Azure Data Studio中运行此查询时,我会遇到一个错误,但看起来不错,但是

SELECT ID / 0 FROM Table1

Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

当我在TryCatch Block中运行查询时,我的PowerShell脚本就会即使我将其包装在TryCatch块中,它也不会输出错误。

因此,我只是想知道如何在PowerShell脚本中捕获SQL语句错误?

I have a query like this in my PowerShell Script

try{
    $Query = "SELECT ID / 0 FROM Tables1"
    Invoke-Sqlcmd -Query $Query -ServerInstance $Global:Server -Database $Global:Database
}
catch {
    "error when running sql $Query "
    $error=  $_
}

The problem I'm having is when I run this query in Azure Data Studio then I get an error and that look fine but

SELECT ID / 0 FROM Table1

Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

when I run the query inside my trycatch block ins my PowerShell script then some reason it's not outputting the error even though I wrap it inside trycatch block.

So I'm just wondering how could I catch the sql statement errors in my PowerShell Script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖正好 2025-02-06 03:04:33

这是由于您的-Command-未失败(Indoke-SQL ...)
因此,根据Powershell的说法,没有什么可“抓住”的,因为该命令有效。

当然,被触发的SQL查询失败了,但是在SQL Server中失败,并将MSG返回到您的PowerShell命令中。

就Powershell而言,一切都是令人振奋的。
(我试图自己找到解决方案,因为我还没有,但很可能会在检查返回msg的球场中以1/0或 - 包含错误

This is due to your -command- not failing (invoke-sql...)
therefor there is nothing to "catch" according to powershell , because the command worked.

Sure , the SQL query that got fired , that one failed , but it fails inside SQL server , and returns a msg to your powershell command.

As far as powershell is concerned ,everything is honky-dorey.
(im trying to find the solution myself , as i dont have it yet , but likely will be somewhere in the ballpark of checking return msg for 1/0 or -contains error

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文