Last Updated: February 25, 2016
· dwimbley

Script to test Sql Server Connection

A useful script to test sql server connectivity should a server's IP address change or a ACL rule change resulting in loss of connection. Could easily alter to run daily and send a mail should the connection go down.





$connectionString = [string]::Format( "server={0};database={1};uid={2};pwd={3};", $ServerName,     $DatabaseName,$Username,$Password) 

$conn = New-Object system.Data.SqlClient.SqlConnection
$conn.connectionstring = $connectionString

switch ($conn.State)
"Open" { Write-Host "Connection Works"; }
Default { Write-Host "The connection is $($conn.State). Error connecting to DB. Check Acl rules or windows firewall"; }


.\Test-SqlServer.ps1 -ServerName <hostname_here> -DatabaseName <db_here> -Username <user_here> -Password <pass_here>