I was not able to find any documentation for the [SqlPowerShellSqlExecutionException]
class, however, by downloading and inspecting the SqlServer
module (specifically, the Microsoft.SqlServer.Management.PSSnapins
assembly) I was able to find that exception class derives directly from [Exception]
(so there is not a general SQL exception type you could catch
instead) and contains exactly one property named SqlError
and of type [SqlError]
.
Looking at that documentation there is, unfortunately, not a nice enumeration property describing the various potential errors, however I do see there is a Number
property. I'm a little confused what the last column of the table on that page is indicating, but it seems like if you write your catch
block like this...
Catch [Microsoft.SqlServer.Management.PowerShell.SqlPowerShellSqlExecutionException]
{
# Error number specified at https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlerror.number#remarks
if ($_.Exception.SqlError.Number -eq -2)
{
Write-Output "Timeout error. Try again"
}
}
...or like this...
Catch [Microsoft.SqlServer.Management.PowerShell.SqlPowerShellSqlExecutionException]
{
# Error number specified at https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlerror.number#remarks
if ($_.Exception.SqlError.Number -eq 258)
{
Write-Output "Timeout error. Try again"
}
}
...that will allow you to specifically target timeout errors. Or perhaps you need to check for both of those error numbers. See Database Engine Events and Errors for a lengthy list of error numbers to match against, and also consider writing your catch
block like this to inspect what Number
you're getting for a timeout error...
Catch [Microsoft.SqlServer.Management.PowerShell.SqlPowerShellSqlExecutionException]
{
$_.Exception.SqlError | Select-Object -Property 'Number', 'Message'
}
There is also an SqlError.Message
property, so as a last resort you could always do something like this...
Catch [Microsoft.SqlServer.Management.PowerShell.SqlPowerShellSqlExecutionException]
{
#TODO: Is $_.Exception.SqlError.Message...
# - ...the same string as $_.Exception.Message ?
# - ...a substring of $_.Exception.Message ?
# - ...more specific than $_.Exception.Message ?
if ($_.Exception.SqlError.Message -eq 'Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.')
{
Write-Output "Timeout error. Try again"
}
}
By the way, though Write-Output
might happen to achieve the goal of writing text to the console, if your intent is to provide feedback to the user then Write-Host
, Write-Information
or Write-Warning
would be more suitable cmdlets for that. See PowerShell difference between Write-Host and Write-Output?.