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"
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.
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.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With