SQL Server How to catch sql query error in powershell

ff29svar  于 2023-05-16  发布在  Shell
关注(0)|答案(1)|浏览(150)

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?

x33g5p2x

x33g5p2x1#

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

相关问题