views:

256

answers:

1

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.

+1  A: 

I can't seem to reproduce the behavior you are seeing. If recreate your function as script rather than a function the ConnectionTimeout property seems to work regardless of whether the server name parameter is bogus or not:

Measure-Command {./get-smoconnection.ps1 'Z03\sq2k8' 2}
Chad Miller
Thank you for testing my code. In the meantime I have tried a C# equivalent of it - setting the timeout and trying to connect to a non existing server, and it works. I will need test the PowerShell script on another machine, but I suspect that it will also work - I have no idea what I could have done to mess up my test computer and it is driving me crazy.
Uros Calakovic