Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2015
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. function Execute-SQL {
  2. param(
  3. [string] $ConnectionStr = "Data Source=SERVER;Initial Catalog=MYDB;Integrated Security=True;Connection Timeout=300000;",
  4. [string] $CommandText = $(throw "Please specify a query."),
  5. [string] $CommandType, #options are "stored procedure" (or "sp") and "nonquery" (or "nq"); any other option is ignored; default is plain ol' query
  6. [hashtable] $CommandParams
  7. )
  8.  
  9. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionStr)
  10. $SqlConnection.Open()
  11. $SqlCmd = new-object System.Data.SqlClient.SqlCommand($CommandText, $SqlConnection)
  12. $SqlCmd.Connection = $SqlConnection
  13. if (($CommandType -eq "stored procedure") -or ($CommandType -eq "sp"))
  14. {
  15. $SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure'
  16. }
  17. if ($CommandParams)
  18. {
  19. foreach ($p in $CommandParams.GetEnumerator())
  20. {
  21. $SqlCmd.Parameters.Add($($p.Name), $($p.Value)) |out-null
  22. }
  23. }
  24. if (($CommandType -eq "nonquery") -or ($CommandType -eq "nq"))
  25. {
  26. $rowsAffected = $sqlcmd.ExecuteNonQuery()
  27. return $rowsAffected
  28. }
  29.  
  30. $adapter = new-object System.Data.SqlClient.SqlDataAdapter
  31. $adapter.SelectCommand = $SqlCmd
  32. $set = new-object data.dataset
  33. try
  34. {
  35. $adapter.fill($set) |out-null
  36. $set
  37. }
  38. catch
  39. {
  40. throw $_.Exception.Message
  41. }
  42. finally
  43. {
  44. $SqlConnection.Close()
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement