Last active
July 16, 2019 23:10
-
-
Save tekkies/0c02befae4201f7f6ea19c117c9637ac to your computer and use it in GitHub Desktop.
Invoke-SqlcmdUsingConnectionString
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
function Get-ConnectionStringComponent($components, $key) { | |
$component = $components | where { $_.StartsWith("$key=") } | |
$value = $component.Split("=")[1] | |
return $value | |
} | |
function Invoke-SqlcmdUsingConnectionString($connectionString, $query){ | |
$components = $connectionString.Split(";") | |
$serverInstance = Get-ConnectionStringComponent $components "Data Source" | |
$database = Get-ConnectionStringComponent $components "Initial Catalog" | |
Write-Host $dataSource | |
Push-Location | |
if($connectionString.Contains("Integrated Security=SSPI")) { | |
$result = Invoke-Sqlcmd ` | |
-ServerInstance "$serverInstance" ` | |
-Database "$database" ` | |
-Query $query | |
} else { | |
$userId = Get-ConnectionStringComponent $components "User ID" | |
$password = Get-ConnectionStringComponent $components "Password" | |
$result = Invoke-Sqlcmd ` | |
-ServerInstance "$serverInstance" ` | |
-Database "$database" ` | |
-Username "$userId" ` | |
-Password "$password" ` | |
-Query $query | |
} | |
Pop-Location | |
return $result | |
} | |
#$connectionString = "Data Source=..." | |
$result = Invoke-SqlcmdUsingConnectionString $connectionString "SELECT @@ServerName" | |
Write-Host $result.ItemArray |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It won't cover all cases, but here it is.