2

我有以下 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 连接超时的经验?先感谢您。

4

1 回答 1

0

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

Measure-Command {./get-smoconnection.ps1 'Z03\sq2k8' 2}
于 2010-05-04T02:33:19.950 回答