Last active
November 25, 2024 17:09
-
-
Save MudraR/b262d2a27a03d5c87d5917e21c019cf4 to your computer and use it in GitHub Desktop.
[MicrosoftSQL Server] Test SQL Connection String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Test-SQLConnection "Data Source=localhost,1433;database=myDB;User ID=myUser;Password=myPassword;" | |
| function Test-SQLConnection { | |
| [CmdletBinding()] | |
| param( | |
| [Parameter(Mandatory=$true, ValueFromPipeline=$true)] | |
| [string] $ConnectionString | |
| ) | |
| process { | |
| $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString | |
| try { | |
| $connectionBuilder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder $ConnectionString | |
| $Server = $connectionBuilder.DataSource | |
| $Database = $connectionBuilder.InitialCatalog | |
| $User = if ($connectionBuilder.IntegratedSecurity) { | |
| "Windows ($env:USERNAME)" | |
| } else { | |
| $connectionBuilder.UserID | |
| } | |
| # Measure the time it takes to open the connection | |
| $connectionTime = Measure-Command { $sqlConnection.Open() } | |
| $sqlConnection.Close() | |
| $Result = @{ | |
| Connection = "Successful" | |
| ElapsedTime = $connectionTime.TotalSeconds | |
| Server = $Server | |
| Database = $Database | |
| User = $User | |
| } | |
| } catch { | |
| $Result = @{ | |
| Connection = "Failed" | |
| ElapsedTime = 0 | |
| Server = $connectionBuilder.DataSource | |
| Database = $connectionBuilder.InitialCatalog | |
| User = if ($connectionBuilder.IntegratedSecurity) { | |
| "Windows ($env:USERNAME)" | |
| } else { | |
| $connectionBuilder.UserID | |
| } | |
| } | |
| } finally { | |
| $sqlConnection.Close() | |
| } | |
| $outputObject = New-Object -Property $Result -TypeName PSObject | |
| Write-Output $outputObject | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment