Created
April 10, 2021 13:10
-
-
Save dhmacher/1a43f84771d1e881c43aa584ea16b742 to your computer and use it in GitHub Desktop.
Run a SQL Server query using .NET (without the "SqlServer" module)
This file contains 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 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