Test Database Connectivity
Often it is needed to test a connection to a SQL Server database. This small PowerShell function can do the trick if you con’t have installed SQL Server Management Studio on your client computer.
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;
}
}
Here is an example of how to use the PowerShell:
Test-SQLConnection "Data Source=localhost;database=myDB;User ID=myUser;Password=myPassword;"
Since the function use a connection-string as input parameter, the function can be used to test both SQL Authentication users and Active Directory integrated users.