Sql server 2008 Sql Server SMO连接超时不工作

Sql server 2008 Sql Server SMO连接超时不工作,sql-server-2008,powershell,smo,connection-timeout,Sql Server 2008,Powershell,Smo,Connection Timeout,我有以下PowerShell代码: function Get-SmoConnection { param ([string] $serverName = "", [int] $connectionTimeout = 0) if($serverName.Length -eq 0) { $serverConnection = New-Object ` Microsoft.SqlServer.Management.Co

我有以下PowerShell代码:

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"
}
除了尝试设置SMO连接超时的部分之外,它似乎可以工作。如果连接成功,我可以验证ServerConnection.ConnectTimeout是否设置为2(秒),但当我为SQL Server实例提供一个假名称时,它仍会尝试连接到它约15秒(我相信这是默认的超时值)


有没有人有设置SMO连接超时的经验?提前谢谢你。

我似乎无法重现你看到的行为。如果将函数重新创建为脚本而不是函数,则无论服务器名称参数是否为伪参数,ConnectionTimeout属性似乎都能工作:

Measure-Command {./get-smoconnection.ps1 'Z03\sq2k8' 2}

我似乎无法重现你所看到的行为。如果将函数重新创建为脚本而不是函数,则无论服务器名称参数是否为伪参数,ConnectionTimeout属性似乎都能工作:

Measure-Command {./get-smoconnection.ps1 'Z03\sq2k8' 2}

谢谢你测试我的代码。与此同时,我尝试了一个C#等效的方法——设置超时并尝试连接到一个不存在的服务器,它可以工作。我需要在另一台机器上测试PowerShell脚本,但我怀疑它也能工作-我不知道我能做些什么来搞乱我的测试计算机,这让我发疯。谢谢你测试我的代码。与此同时,我尝试了一个C#等效的方法——设置超时并尝试连接到一个不存在的服务器,它可以工作。我需要在另一台机器上测试PowerShell脚本,但我怀疑它也能工作-我不知道我能做些什么来搞乱我的测试计算机,这让我发疯。我看到了相同的行为:如果我同时将
StatementTimeout
ConnectTimeout
设置为1(秒)然后尝试连接到一个不存在的服务器。第一次超时需要10秒。但是如果我立即重新尝试test命令(连接到
主机
DB),它会更快超时,但仍然与设置不一致。恼人。我看到了相同的行为:如果我将
StatementTimeout
ConnectTimeout
都设置为1(秒),然后尝试连接到不存在的服务器,则第一次超时需要约10秒。但是如果我立即重新尝试test命令(连接到
主机
DB),它会更快超时,但仍然与设置不一致。烦人的