Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Try Catch invoke-sqlcmd

I am having problems catching an error in PowerShell when a connection fails to a SQL Server using Invoke-Sqlcmd. This is some generic code to demonstrate the issue:

CLS
$server = "Localhost\fake"
try
{
    Invoke-Sqlcmd -Query "SELECT DB_NAME() as [Database]" -Server $server
}
catch
{
    Write-Host "Error connecting to server " $server
}

I get the following error:

Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

I was expecting to get the one line statement: "Error connecting to server Localhost\fake"

like image 953
Eric Z Avatar asked Nov 28 '12 17:11

Eric Z


People also ask

What is PowerShell’s invoke-SQLCMD?

As we’ve seen, PowerShell’s Invoke-SqlCmd is a convenient tool in which we can create objects, read and write data to and from SQL Server (with direct or file input), and save queries to files without significant development work. While we’ve looked at a few examples that we’ll use frequently, this function has more capability than what’s covered.

What is invoke-SQLCMD in SQL Server?

The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.

What are some examples of try-catch in PowerShell?

Examples of Try-catch in PowerShell. The below is a sample usage of Try, catch block: Code: try {dfdgfdfgf sfsdf dsfdfdsf} catch {write-host "Exception caught"} Output:

What is a try catch block in PowerShell?

Understanding Try-Catch. In PowerShell, the error handling is done through trial and catch blocks. The try block will have the code, that may likely throw an error. The catch block contains the code or action to be executed in case of an error that is thrown by the try block.


1 Answers

It would appear that error is considered non-terminating which is a bit odd. Try the Invoke-SqlCommand with an additional parameter: -ErrorAction Stop. If there error is non-terminating, this will convert it to a terminating error that you can catch.

like image 119
Keith Hill Avatar answered Oct 04 '22 06:10

Keith Hill