Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Execute-SQL {
- param(
- [string] $ConnectionStr = "Data Source=SERVER;Initial Catalog=MYDB;Integrated Security=True;Connection Timeout=300000;",
- [string] $CommandText = $(throw "Please specify a query."),
- [string] $CommandType, #options are "stored procedure" (or "sp") and "nonquery" (or "nq"); any other option is ignored; default is plain ol' query
- [hashtable] $CommandParams
- )
- $SqlConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionStr)
- $SqlConnection.Open()
- $SqlCmd = new-object System.Data.SqlClient.SqlCommand($CommandText, $SqlConnection)
- $SqlCmd.Connection = $SqlConnection
- if (($CommandType -eq "stored procedure") -or ($CommandType -eq "sp"))
- {
- $SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure'
- }
- if ($CommandParams)
- {
- foreach ($p in $CommandParams.GetEnumerator())
- {
- $SqlCmd.Parameters.Add($($p.Name), $($p.Value)) |out-null
- }
- }
- if (($CommandType -eq "nonquery") -or ($CommandType -eq "nq"))
- {
- $rowsAffected = $sqlcmd.ExecuteNonQuery()
- return $rowsAffected
- }
- $adapter = new-object System.Data.SqlClient.SqlDataAdapter
- $adapter.SelectCommand = $SqlCmd
- $set = new-object data.dataset
- try
- {
- $adapter.fill($set) |out-null
- $set
- }
- catch
- {
- throw $_.Exception.Message
- }
- finally
- {
- $SqlConnection.Close()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement