我有以下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连接超时的经验?提前谢谢。
答案 0 :(得分:0)
我似乎无法重现你所看到的行为。如果将函数重新创建为脚本而不是函数,则无论服务器名称参数是否为假,ConnectionTimeout属性似乎都能正常工作:
Measure-Command {./get-smoconnection.ps1 'Z03\sq2k8' 2}