Skip to content

Instantly share code, notes, and snippets.

@sean-m
Last active December 15, 2020 18:12
Show Gist options
  • Save sean-m/a616d7e2f4f549103fbce66c78065814 to your computer and use it in GitHub Desktop.
Save sean-m/a616d7e2f4f549103fbce66c78065814 to your computer and use it in GitHub Desktop.
Modified version of a function posted to Technet, this one attempts to handle GO statements so can take auto generated SQL from SSMS.
function Invoke-SQL {
param(
[string] $connectionString = ".\SQLEXPRESS",
[string] $sqlCommand = $(throw "Please specify a query."),
[hashtable] $parameters = @{},
[switch] $splitOnGo
)
$queries = @()
## Split sqlCommand on GO keyword.
## GO isn't strictly proper SQL, it's a feature only honored by SSMS
## to break up your SQL scripts.
if ($splitOnGo -and ($parameters.Count -gt 0)) {
throw "Cannot execute parameterized query while splitting on GO!"
return
}
if ($splitOnGo) {
$sql_text = ($sqlCommand.Split([Environment]::NewLine) | % { $_.Trim() }) -join "`n"
$go_pattern = New-Object System.Text.RegularExpressions.Regex ('(?i)^GO', [System.Text.RegularExpressions.RegexOptions]::Multiline)
$queries += $go_pattern.Split($sql_text) | ? { $_ -notlike "GO" } | ? { $_ }
}
else {
$queries += $sqlCommand
}
try {
$connection = New-Object System.Data.SqlClient.SqlConnection ($connectionString)
foreach ($query in $queries) {
$command = New-Object System.Data.SqlClient.SqlCommand ($query,$connection)
if ($parameters.Count -gt 0) {
foreach($p in $parameters.Keys){
[Void] $command.Parameters.AddWithValue("@$p",$parameters[$p])
}
}
if ($connection.State -notlike 'Open') { $connection.Open() }
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataset) | Out-Null
$dataset.Tables
}
}
finally {
if ($connection) { $connection.Close() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment