@@ -74,6 +74,10 @@ function Invoke-DBOQuery {
74
74
. PARAMETER As
75
75
Specifies output type. Valid options for this parameter are 'DataSet', 'DataTable', 'DataRow', 'PSObject', and 'SingleValue'
76
76
77
+ . PARAMETER Parameter
78
+ Uses values in specified hashtable as parameters inside the SQL query.
79
+ For example, <Invoke-DBOQuery -Query 'SELECT @p1' -Parameter @{ p1 = 1 }> would return "1" on SQL Server.
80
+
77
81
. PARAMETER Confirm
78
82
Prompts to confirm certain actions
79
83
@@ -142,7 +146,9 @@ function Invoke-DBOQuery {
142
146
[string ]$Type = (Get-DBODefaultSetting - Name rdbms.type - Value),
143
147
[ValidateSet (" DataSet" , " DataTable" , " DataRow" , " PSObject" , " SingleValue" )]
144
148
[string ]
145
- $As = " DataRow"
149
+ $As = " DataRow" ,
150
+ [Alias (' SqlParameters' , ' SqlParameter' , ' Parameters' )]
151
+ [System.Collections.IDictionary ]$Parameter
146
152
)
147
153
148
154
begin {
@@ -178,7 +184,13 @@ function Invoke-DBOQuery {
178
184
if (-Not $config.Silent ) {
179
185
$dbUpConnection.IsScriptOutputLogged = $true
180
186
}
181
- $managedConnection = $dbUpConnection.OperationStarting ($dbUpLog , $null )
187
+ try {
188
+ $managedConnection = $dbUpConnection.OperationStarting ($dbUpLog , $null )
189
+ }
190
+ catch {
191
+ Stop-PSFFunction - EnableException $true - Message " Failed to connect to the server" - ErrorRecord $_
192
+ return
193
+ }
182
194
if ($Query ) {
183
195
$queryText = $Query
184
196
}
@@ -211,12 +223,23 @@ function Invoke-DBOQuery {
211
223
if ($PSCmdlet.ShouldProcess (" Executing query $qCount " , $config.SqlInstance )) {
212
224
foreach ($splitQuery in $dbUpConnection.SplitScriptIntoCommands ($queryItem )) {
213
225
$dt = [System.Data.DataTable ]::new()
214
- $rows = $dbUpConnection.ExecuteCommandsWithManagedConnection ( [Func [Func [Data.IDbCommand ], [ pscustomobject ] ]] {
226
+ $rows = $dbUpConnection.ExecuteCommandsWithManagedConnection ( [Func [Func [Data.IDbCommand ], pscustomobject ]] {
215
227
Param (
216
228
$dbCommandFactory
217
229
)
230
+ # Compile the parameters as Expression functions
231
+ $exp = [System.Linq.Expressions.Expression ]
232
+ $parameterList = @ ()
233
+ foreach ($key in $Parameter.Keys ) {
234
+ $param = $exp ::Parameter([string ], $key )
235
+ $value = $exp ::Constant($Parameter .$key )
236
+ $body = $exp ::Convert($value , [System.Object ])
237
+ $lambda = $exp ::Lambda([Func [string , object ]], $body , $param )
238
+ $parameterList += $lambda
239
+ }
240
+ # Initiating the AdHocSqlRunner
218
241
$sqlRunner = [DbUp.Helpers.AdHocSqlRunner ]::new($dbCommandFactory , $dbUpSqlParser , $config.Schema )
219
- return $sqlRunner.ExecuteReader ($splitQuery )
242
+ return $sqlRunner.ExecuteReader ($splitQuery , $parameterList )
220
243
})
221
244
$rowCount = ($rows | Measure-Object ).Count
222
245
if ($rowCount -gt 0 ) {
0 commit comments