Skip to content

Instantly share code, notes, and snippets.

@niaher
Created October 25, 2021 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niaher/abe43d5d7d5fb9c4fde0f97648539964 to your computer and use it in GitHub Desktop.
Save niaher/abe43d5d7d5fb9c4fde0f97648539964 to your computer and use it in GitHub Desktop.
Test connectivity to a local or remote SQL Server database using PowerShell
function Test-SqlConnection {
param(
[Parameter(Mandatory)]
[string]$ConnectionString
)
$ErrorActionPreference = 'Stop'
try {
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
$sqlConnection.Open()
## This will run if the Open() method does not throw an exception
$true
} catch {
$false
} finally {
## Close the connection when we're done
$sqlConnection.Close()
}
}
Test-SqlConnection -ConnectionString 'Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=true;Pooling=False;Connect Timeout=10;'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment