测试数据库连接

时间:2015-03-24 09:34:18

标签: powershell

有一种简单的方法可以使用PowerShell测试从客户端连接到MS SQL Server实例的连接(不加载任何SQL程序集)吗?

MS Sql: Servername \ Instance Port 1433

如何使用PowerShell从普通客户端测试与服务器的连接?

3 个答案:

答案 0 :(得分:42)

使用SqlConnection class测试连接。您不必加载任何SQL程序集

辅助功能:

function Test-SQLConnection
{    
    [OutputType([bool])]
    Param
    (
        [Parameter(Mandatory=$true,
                    ValueFromPipelineByPropertyName=$true,
                    Position=0)]
        $ConnectionString
    )
    try
    {
        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString;
        $sqlConnection.Open();
        $sqlConnection.Close();

        return $true;
    }
    catch
    {
        return $false;
    }
}

用法示例:

Test-SQLConnection "Data Source=localhost;database=myDB;User ID=myUser;Password=myPassword;"

答案 1 :(得分:9)

这与Martin的答案基本相同,只是从参数构建连接字符串,并测量连接所需的时间。

e.g:

Test-SQLDatabase -Server SQLServer -Database SomeDB -Username SQLUser -Password password

Test-SQLDatabase -Server Server1\SQLExpress -Database SomeDB -UseWindowsAuthentication

function Test-SQLDatabase 
{
    param( 
    [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True)] [string] $Server,
    [Parameter(Position=1, Mandatory=$True)] [string] $Database,
    [Parameter(Position=2, Mandatory=$True, ParameterSetName="SQLAuth")] [string] $Username,
    [Parameter(Position=3, Mandatory=$True, ParameterSetName="SQLAuth")] [string] $Password,
    [Parameter(Position=2, Mandatory=$True, ParameterSetName="WindowsAuth")] [switch] $UseWindowsAuthentication
    )

    # connect to the database, then immediatly close the connection. If an exception occurrs it indicates the conneciton was not successful. 
    process { 
        $dbConnection = New-Object System.Data.SqlClient.SqlConnection
        if (!$UseWindowsAuthentication) {
            $dbConnection.ConnectionString = "Data Source=$Server; uid=$Username; pwd=$Password; Database=$Database;Integrated Security=False"
            $authentication = "SQL ($Username)"
        }
        else {
            $dbConnection.ConnectionString = "Data Source=$Server; Database=$Database;Integrated Security=True;"
            $authentication = "Windows ($env:USERNAME)"
        }
        try {
            $connectionTime = measure-command {$dbConnection.Open()}
            $Result = @{
                Connection = "Successful"
                ElapsedTime = $connectionTime.TotalSeconds
                Server = $Server
                Database = $Database
                User = $authentication}
        }
        # exceptions will be raised if the database connection failed.
        catch {
                $Result = @{
                Connection = "Failed"
                ElapsedTime = $connectionTime.TotalSeconds
                Server = $Server
                Database = $Database
                User = $authentication}
        }
        Finally{
            # close the database connection
            $dbConnection.Close()
            #return the results as an object
            $outputObject = New-Object -Property $Result -TypeName psobject
            write-output $outputObject 
        }
    }
}

答案 2 :(得分:7)

这取决于你真正想要测试的内容。如果您只是想验证是否可以连接到远程主机上的端口,则会执行以下操作:

$server = 'servername'
$port   = 1433

$tcp = New-Object Net.Sockets.TcpClient
if ([void]$tcp.Connect($server, $port)) {
  'connected'
} else {
  'not connected'
}
$tcp.Dispose()

如果要验证是否可以建立与SQL Server实例的连接,则需要执行以下操作:

$dbhost = 'servername'
$dbinst = 'instance'
$dbname = 'master'

$username = ...
$password = ...

$cs = "Server=$dbhost\$dbinst;Database=$dbname;User Id=$username;" +
      "Password=$password;"

$cn = New-Object -COM 'ADODB.Connection'
$cn.ConnectionString = $cs
try {
  $cn.Open()
  if ($cn.State -eq 1) {
    'connected'
    $cn.Close()
  } else {
    'not connected'
  }
} catch {
  'not connected'
}