Skip to content

Instantly share code, notes, and snippets.

@dhmacher
Created April 10, 2021 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhmacher/1a43f84771d1e881c43aa584ea16b742 to your computer and use it in GitHub Desktop.
Save dhmacher/1a43f84771d1e881c43aa584ea16b742 to your computer and use it in GitHub Desktop.
Run a SQL Server query using .NET (without the "SqlServer" module)
Function Invoke-ParamQuery {
param(
[String]$Query,
$Parameters=@{},
[Data.SqlClient.SqlConnection]$Conn,
[int]$Timeout=3,
[switch]$CloseConn,
[switch]$DiscardResults
)
if ($conn.State -eq "Closed") {
$conn.Open()
}
$cmd = New-Object System.Data.SqlClient.SqlCommand($Query,$Conn)
$cmd.CommandTimeout = $Timeout
ForEach ($p in $Parameters.Keys) {
[void]$cmd.Parameters.AddWithValue("@$p",$Parameters[$p])
}
$dataTable = New-Object System.Data.DataTable
if ($DiscardResults) {
# Execute without result sets
$rowsAffected = $cmd.ExecuteNonQuery()
} else {
# Create a data table that collect the results of the query
$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dataAdapter.Fill($dataTable) | Out-Null
}
If ($CloseConn -and $conn.State -eq "Open") {
$conn.Close()
$conn.Dispose()
}
return $dataTable
}
Function New-Connection {
param(
[string]$Instance,
[string]$Database
)
$conn = New-Object Data.SqlClient.SqlConnection "Server=$Instance;Initial Catalog=$Database;Integrated Security=True"
return $conn
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment