1
+ <#
2
+ . SYNOPSIS
3
+ Execute provided SQL against provided Server Instance accepts parameters
4
+ . DESCRIPTION
5
+ Will execute SQL against instance, If UserName and password are not provided then integrated security is used.
6
+ if TargetDatabase not provided then query should contain fully qualified paths for query.
7
+ . PARAMETER ServerInstance
8
+ Name of instance to execute against
9
+ . PARAMETER Query
10
+ String Query to run
11
+ . PARAMETER Parameters
12
+ Dictionary of parameter names and values.
13
+ . PARAMETER TargetDatabase
14
+ If Provided will define 'Initial Catalog' parameter on connection string
15
+ . PARAMETER NonQuery
16
+ States that this query does not return results i.e. Action Queries (CREATE, ALTER, DROP, INSERT, UPDATE, DELETE)
17
+ . PARAMETER UserName
18
+ User to execute as
19
+ . PARAMETER Password
20
+ SecureString password to utilise
21
+ . EXAMPLE
22
+ Invoke-Sql -ServerInstance localhost\sqlexpress -Query "SELECT * FROM Person"
23
+ Will execute and return object of results
24
+ . EXAMPLE
25
+ Invoke-Sql -ServerInstance localhost\sqlexpress -Query "SELECT FirstName, LastName FROM Person WHERE FirstName=@fname" -Parameters @{fname = 'John'}
26
+ Will execute the query and return object of the results
27
+ . EXAMPLE
28
+ Invoke-Sql -ServerInstance localhost\sqlexpress -Query "INSERT INTO Person(FirstName, LastName) VALUES('Jane', 'Doe')" -NonQuery
29
+ Will execute returning if number of rows affected.
30
+ . EXAMPLE
31
+ Invoke-Sql -ServerInstance localhost\sqlexpress -Query "INSERT INTO Person(FirstName, LastName) VALUES(@fname, @lname)" -Parameter @{fname='Jane'; lname='Doe'} -NonQuery
32
+ Will execute returning if number of rows affected.
33
+ . NOTES
34
+ Only executable against Microsoft SQL Server instances.
35
+ #>
36
+ function Invoke-Sql {
37
+ [CmdletBinding ()]
38
+ param (
39
+ [parameter (Mandatory = $true )]
40
+ [String ] $ServerInstance ,
41
+
42
+ [parameter (Mandatory = $true )]
43
+ [string ] $Query ,
44
+
45
+ [parameter (Mandatory = $false )]
46
+ [hashtable ]$Parameters ,
47
+
48
+ [parameter (Mandatory = $false )]
49
+ [string ] $TargetDatabase ,
50
+
51
+ [parameter (Mandatory = $false )]
52
+ [switch ] $NonQuery ,
53
+
54
+ [parameter (HelpMessage = " UserName to use" )]
55
+ [string ]$UserName ,
56
+
57
+ [parameter (Mandatory = $false )]
58
+ [securestring ]$Password
59
+ )
60
+
61
+ begin {
62
+ $connectionString = " Data Source=$ServerInstance ;"
63
+ if ($TargetDatabase ) {
64
+ $connectionString += " Initial Catalog=$TargetDatabase ;"
65
+ }
66
+
67
+ $conn = New-Object system.data.SqlClient.sqlconnection
68
+ if ($UserName -and $Password ) {
69
+ Write-Verbose " Using specified credentials"
70
+ $creds = New-Object System.Data.SqlClient.SqlCredential($UserName , $Password )
71
+ }
72
+ else {
73
+ $connectionString += " Integrated Security = True;"
74
+ }
75
+
76
+ $conn.ConnectionString = $connectionString
77
+ if ($null -ne $creds ) {
78
+ $conn.Credential = $creds
79
+ }
80
+ }
81
+
82
+ process {
83
+ try {
84
+ if ($NonQuery ) {
85
+ # Execute as NonQuery
86
+ Write-verbose " Creating SQL Command..."
87
+ $cmd = New-Object system.data.SqlClient.SqlCommand($Query , $conn )
88
+ if ($Parameters.Count -gt 0 ) {
89
+ $cmd.Parameters.Clear ()
90
+ foreach ($p in $Parameters.Keys ) {
91
+ [void ] $cmd.Parameters.AddWithValue (" @$p " , $Parameters [$p ])
92
+ }
93
+ }
94
+ Write-Verbose " Opening SQL Connection..."
95
+ $conn.Open ()
96
+ Write-Verbose " Executing SQL Command..."
97
+ Write-Verbose $cmd.CommandText
98
+ $result = $cmd.ExecuteNonQuery ()
99
+ if ($result -gt 0 ) {
100
+ Write-Verbose " Successfully Executed Command"
101
+ return $result
102
+ }
103
+ else {
104
+ Write-Error $Error
105
+ }
106
+ }
107
+ else {
108
+ # then execute as required returning object of results
109
+ $cmd = New-Object system.data.SqlClient.SqlCommand($Query , $conn )
110
+ if ($Parameters.Count -gt 0 ) {
111
+ $cmd.Parameters.Clear ()
112
+ foreach ($p in $Parameters.Keys ) {
113
+ [void ] $cmd.Parameters.AddWithValue (" @$p " , $Parameters [$p ])
114
+ }
115
+ }
116
+ Write-Verbose " Opening SQL Connection..."
117
+ $conn.Open ()
118
+ Write-Verbose $cmd.CommandText
119
+ $reader = $cmd.ExecuteReader () | Out-Null
120
+ $results = @ ()
121
+ while ($reader.Read ()) {
122
+ $row = @ {}
123
+ for ($i = 0 ; $i -lt $reader.FieldCount ; $i ++ ) {
124
+ Write-Verbose " Adding $ ( $reader.GetName ($i )) to psobject"
125
+ $row [$reader.GetName ($i )] = $reader.GetValue ($i )
126
+ }
127
+ $results += New-Object psobject - Property $row
128
+ }
129
+ $conn.Close ()
130
+ return $results
131
+ }
132
+ }
133
+ catch [system.data.SqlClient.sqlexception ] {
134
+ Write-Error " One or more of the rows being affected were locked. Please check your query and data then try again."
135
+ }
136
+ catch {
137
+ Write-Error " An error occurred while attempting to open the database connection and execute a command"
138
+ }
139
+ finally {
140
+ if ($conn.State -eq ' Open' ) {
141
+ Write-Verbose " Closing connection..."
142
+ $conn.Close ()
143
+ }
144
+ }
145
+ }
146
+
147
+ end {
148
+ $conn.Dispose ()
149
+ }
150
+ }
0 commit comments