如何在PowerShell中捕获SQL查询错误
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是由于您的-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