Sql Server SMO connection timeout not working
- by Uros Calakovic
I have the following PowerShell code:
function Get-SmoConnection
{
param
([string] $serverName = "", [int] $connectionTimeout = 0)
if($serverName.Length -eq 0)
{
$serverConnection = New-Object `
Microsoft.SqlServer.Management.Common.ServerConnection
}
else
{
$serverConnection = New-Object `
Microsoft.SqlServer.Management.Common.ServerConnection($serverName)
}
if($connectionTimeout -ne 0)
{
$serverConnection.ConnectTimeout = $connectionTimeout
}
try
{
$serverConnection.Connect()
$serverConnection
}
catch [system.Management.Automation.MethodInvocationException]
{
$null
}
}
$connection = get-smoconnection "ServerName" 2
if($connection -ne $null)
{
Write-Host $connection.ServerInstance
Write-Host $connection.ConnectTimeout
}
else
{
Write-Host "Connection could not be established"
}
It seems to work, except for the part that attempts to set the SMO connection timeout. If the connection is successful, I can verify that ServerConnection.ConnectTimeout is set to 2 (seconds), but when I supply a bogus name for the SQL Server instance, it still attempts to connect to it for ~ 15 seconds (which is I believe the default timeout value).
Does anyone have experience with setting SMO connection timeout? Thank you in advance.