|
1 |
| -function Invoke-Sqlcmd2 |
| 1 | +function Invoke-Sqlcmd2 |
2 | 2 | {
|
3 |
| - <# |
4 |
| - .SYNOPSIS |
5 |
| - Runs a T-SQL script. |
| 3 | + <# |
| 4 | + .SYNOPSIS |
| 5 | + Runs a T-SQL script. |
6 | 6 |
|
7 |
| - .DESCRIPTION |
| 7 | + .DESCRIPTION |
8 | 8 | Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified.
|
9 |
| - Paramaterized queries are supported. |
| 9 | + Paramaterized queries are supported. |
10 | 10 |
|
11 | 11 | Help details below borrowed from Invoke-Sqlcmd
|
12 | 12 |
|
|
26 | 26 |
|
27 | 27 | .PARAMETER Credential
|
28 | 28 | Specifies A PSCredential for SQL Server Authentication connection to an instance of the Database Engine.
|
29 |
| - |
| 29 | +
|
30 | 30 | If -Credential is not specified, Invoke-Sqlcmd attempts a Windows Authentication connection using the Windows account running the PowerShell session.
|
31 |
| - |
| 31 | +
|
32 | 32 | SECURITY NOTE: If you use the -Debug switch, the connectionstring including plain text password will be sent to the debug stream.
|
33 | 33 |
|
34 | 34 | .PARAMETER Encrypt
|
|
41 | 41 | Specifies the number of seconds when Invoke-Sqlcmd2 times out if it cannot successfully connect to an instance of the Database Engine. The timeout value must be an integer between 0 and 65534. If 0 is specified, connection attempts do not time out.
|
42 | 42 |
|
43 | 43 | .PARAMETER As
|
44 |
| - Specifies output type - DataSet, DataTable, array of DataRow, PSObject or Single Value |
| 44 | + Specifies output type - DataSet, DataTable, array of DataRow, PSObject or Single Value |
45 | 45 |
|
46 | 46 | PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/
|
47 | 47 |
|
|
59 | 59 | If specified, use an existing SQLConnection.
|
60 | 60 | We attempt to open this connection if it is closed
|
61 | 61 |
|
62 |
| - .INPUTS |
63 |
| - None |
64 |
| - You cannot pipe objects to Invoke-Sqlcmd2 |
| 62 | + .INPUTS |
| 63 | + None |
| 64 | + You cannot pipe objects to Invoke-Sqlcmd2 |
65 | 65 |
|
66 | 66 | .OUTPUTS
|
67 | 67 | As PSObject: System.Management.Automation.PSCustomObject
|
|
70 | 70 | As DataSet: System.Data.DataTableCollectionSystem.Data.DataSet
|
71 | 71 | As SingleValue: Dependent on data type in first column.
|
72 | 72 |
|
73 |
| - .EXAMPLE |
74 |
| - Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" |
75 |
| - |
76 |
| - This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. |
77 |
| - StartTime |
78 |
| - ----------- |
79 |
| - 2010-08-12 21:21:03.593 |
| 73 | + .EXAMPLE |
| 74 | + Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" |
| 75 | +
|
| 76 | + This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. |
| 77 | + StartTime |
| 78 | + ----------- |
| 79 | + 2010-08-12 21:21:03.593 |
80 | 80 |
|
81 |
| - .EXAMPLE |
82 |
| - Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -InputFile "C:\MyFolder\tsqlscript.sql" | Out-File -filePath "C:\MyFolder\tsqlscript.rpt" |
83 |
| - |
84 |
| - This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. |
| 81 | + .EXAMPLE |
| 82 | + Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -InputFile "C:\MyFolder\tsqlscript.sql" | Out-File -filePath "C:\MyFolder\tsqlscript.rpt" |
| 83 | +
|
| 84 | + This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. |
85 | 85 |
|
86 |
| - .EXAMPLE |
87 |
| - Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -Query "PRINT 'hello world'" -Verbose |
| 86 | + .EXAMPLE |
| 87 | + Invoke-Sqlcmd2 -ServerInstance "MyComputer\MyInstance" -Query "PRINT 'hello world'" -Verbose |
88 | 88 |
|
89 |
| - This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. |
90 |
| - VERBOSE: hello world |
| 89 | + This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. |
| 90 | + VERBOSE: hello world |
91 | 91 |
|
92 | 92 | .EXAMPLE
|
93 | 93 | Invoke-Sqlcmd2 -ServerInstance MyServer\MyInstance -Query "SELECT ServerName, VCNumCPU FROM tblServerInfo" -as PSObject | ?{$_.VCNumCPU -gt 8}
|
94 | 94 | Invoke-Sqlcmd2 -ServerInstance MyServer\MyInstance -Query "SELECT ServerName, VCNumCPU FROM tblServerInfo" -as PSObject | ?{$_.VCNumCPU}
|
95 | 95 |
|
96 | 96 | This example uses the PSObject output type to allow more flexibility when working with results.
|
97 |
| - |
| 97 | +
|
98 | 98 | If we used DataRow rather than PSObject, we would see the following behavior:
|
99 | 99 | Each row where VCNumCPU does not exist would produce an error in the first example
|
100 | 100 | Results would include rows where VCNumCPU has DBNull value in the second example
|
|
103 | 103 | 'Instance1', 'Server1/Instance1', 'Server2' | Invoke-Sqlcmd2 -query "Sp_databases" -as psobject -AppendServerInstance
|
104 | 104 |
|
105 | 105 | This example lists databases for each instance. It includes a column for the ServerInstance in question.
|
106 |
| - DATABASE_NAME DATABASE_SIZE REMARKS ServerInstance |
107 |
| - ------------- ------------- ------- -------------- |
108 |
| - REDACTED 88320 Instance1 |
109 |
| - master 17920 Instance1 |
110 |
| - ... |
111 |
| - msdb 618112 Server1/Instance1 |
| 106 | + DATABASE_NAME DATABASE_SIZE REMARKS ServerInstance |
| 107 | + ------------- ------------- ------- -------------- |
| 108 | + REDACTED 88320 Instance1 |
| 109 | + master 17920 Instance1 |
| 110 | + ... |
| 111 | + msdb 618112 Server1/Instance1 |
112 | 112 | tempdb 563200 Server1/Instance1
|
113 |
| - ... |
114 |
| - OperationsManager 20480000 Server2 |
| 113 | + ... |
| 114 | + OperationsManager 20480000 Server2 |
115 | 115 |
|
116 | 116 | .EXAMPLE
|
117 | 117 | #Construct a query using SQL parameters
|
118 | 118 | $Query = "SELECT ServerName, VCServerClass, VCServerContact FROM tblServerInfo WHERE VCServerContact LIKE @VCServerContact AND VCServerClass LIKE @VCServerClass"
|
119 | 119 |
|
120 | 120 | #Run the query, specifying values for SQL parameters
|
121 | 121 | Invoke-Sqlcmd2 -ServerInstance SomeServer\NamedInstance -Database ServerDB -query $query -SqlParameters @{ VCServerContact="%cookiemonster%"; VCServerClass="Prod" }
|
122 |
| - |
123 |
| - ServerName VCServerClass VCServerContact |
124 |
| - ---------- ------------- --------------- |
125 |
| - SomeServer1 Prod cookiemonster, blah |
126 |
| - SomeServer2 Prod cookiemonster |
127 |
| - SomeServer3 Prod blah, cookiemonster |
| 122 | +
|
| 123 | + ServerName VCServerClass VCServerContact |
| 124 | + ---------- ------------- --------------- |
| 125 | + SomeServer1 Prod cookiemonster, blah |
| 126 | + SomeServer2 Prod cookiemonster |
| 127 | + SomeServer3 Prod blah, cookiemonster |
128 | 128 |
|
129 | 129 | .EXAMPLE
|
130 |
| - Invoke-Sqlcmd2 -SQLConnection $Conn -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" |
131 |
| - |
| 130 | + Invoke-Sqlcmd2 -SQLConnection $Conn -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" |
| 131 | +
|
132 | 132 | This example uses an existing SQLConnection and runs a basic T-SQL query against it
|
133 | 133 |
|
134 |
| - StartTime |
135 |
| - ----------- |
136 |
| - 2010-08-12 21:21:03.593 |
| 134 | + StartTime |
| 135 | + ----------- |
| 136 | + 2010-08-12 21:21:03.593 |
137 | 137 |
|
138 | 138 |
|
139 |
| - .NOTES |
140 |
| - Version History |
| 139 | + .NOTES |
| 140 | + Version History |
141 | 141 | poshcode.org - http://poshcode.org/4967
|
142 |
| - v1.0 - Chad Miller - Initial release |
143 |
| - v1.1 - Chad Miller - Fixed Issue with connection closing |
144 |
| - v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation |
145 |
| - v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type |
| 142 | + v1.0 - Chad Miller - Initial release |
| 143 | + v1.1 - Chad Miller - Fixed Issue with connection closing |
| 144 | + v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation |
| 145 | + v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type |
146 | 146 | v1.4 - Justin Dearing <zippy1981 _at_ gmail.com> - Added the ability to pass parameters to the query.
|
147 | 147 | v1.4.1 - Paul Bryson <atamido _at_ gmail.com> - Added fix to check for null values in parameterized queries and replace with [DBNull]
|
148 | 148 | v1.5 - Joel Bennett - add SingleValue output option
|
149 | 149 | v1.5.1 - RamblingCookieMonster - Added ParameterSets, set Query and InputFile to mandatory
|
150 | 150 | v1.5.2 - RamblingCookieMonster - Added DBNullToNull switch and code from Dave Wyatt. Added parameters to comment based help (need someone with SQL expertise to verify these)
|
151 |
| - |
| 151 | +
|
152 | 152 | github.com - https://github.com/RamblingCookieMonster/PowerShell
|
153 | 153 | v1.5.3 - RamblingCookieMonster - Replaced DBNullToNull param with PSObject Output option. Added credential support. Added pipeline support for ServerInstance. Added to GitHub
|
154 | 154 | - Added AppendServerInstance switch.
|
|
202 | 202 | ValueFromRemainingArguments=$false)]
|
203 | 203 | [string]
|
204 | 204 | $Database,
|
205 |
| - |
| 205 | + |
206 | 206 | [Parameter( ParameterSetName='Ins-Que',
|
207 | 207 | Position=2,
|
208 | 208 | Mandatory=$true,
|
|
215 | 215 | ValueFromRemainingArguments=$false )]
|
216 | 216 | [string]
|
217 | 217 | $Query,
|
218 |
| - |
| 218 | + |
219 | 219 | [Parameter( ParameterSetName='Ins-Fil',
|
220 | 220 | Position=2,
|
221 | 221 | Mandatory=$true,
|
|
229 | 229 | [ValidateScript({ Test-Path $_ })]
|
230 | 230 | [string]
|
231 | 231 | $InputFile,
|
232 |
| - |
| 232 | + |
233 | 233 | [Parameter( ParameterSetName='Ins-Que',
|
234 | 234 | Position=3,
|
235 | 235 | Mandatory=$false,
|
|
251 | 251 | Position=4,
|
252 | 252 | Mandatory=$false,
|
253 | 253 | ValueFromRemainingArguments=$false)]
|
254 |
| - [switch] |
| 254 | + [switch] |
255 | 255 | $Encrypt,
|
256 | 256 |
|
257 | 257 | [Parameter( Position=5,
|
|
260 | 260 | ValueFromRemainingArguments=$false )]
|
261 | 261 | [Int32]
|
262 | 262 | $QueryTimeout=600,
|
263 |
| - |
| 263 | + |
264 | 264 | [Parameter( ParameterSetName='Ins-Fil',
|
265 | 265 | Position=6,
|
266 | 266 | Mandatory=$false,
|
|
273 | 273 | ValueFromRemainingArguments=$false )]
|
274 | 274 | [Int32]
|
275 | 275 | $ConnectionTimeout=15,
|
276 |
| - |
| 276 | + |
277 | 277 | [Parameter( Position=7,
|
278 | 278 | Mandatory=$false,
|
279 | 279 | ValueFromPipelineByPropertyName=$true,
|
280 | 280 | ValueFromRemainingArguments=$false )]
|
281 | 281 | [ValidateSet("DataSet", "DataTable", "DataRow","PSObject","SingleValue")]
|
282 | 282 | [string]
|
283 | 283 | $As="DataRow",
|
284 |
| - |
| 284 | + |
285 | 285 | [Parameter( Position=8,
|
286 | 286 | Mandatory=$false,
|
287 | 287 | ValueFromPipelineByPropertyName=$true,
|
|
310 | 310 | [ValidateNotNullOrEmpty()]
|
311 | 311 | [System.Data.SqlClient.SQLConnection]
|
312 | 312 | $SQLConnection
|
313 |
| - ) |
| 313 | + ) |
314 | 314 |
|
315 | 315 | Begin
|
316 | 316 | {
|
317 |
| - if ($InputFile) |
318 |
| - { |
319 |
| - $filePath = $(Resolve-Path $InputFile).path |
320 |
| - $Query = [System.IO.File]::ReadAllText("$filePath") |
| 317 | + if ($InputFile) |
| 318 | + { |
| 319 | + $filePath = $(Resolve-Path $InputFile).path |
| 320 | + $Query = [System.IO.File]::ReadAllText("$filePath") |
321 | 321 | }
|
322 | 322 |
|
323 | 323 | Write-Verbose "Running Invoke-Sqlcmd2 with ParameterSet '$($PSCmdlet.ParameterSetName)'. Performing query '$Query'"
|
|
421 | 421 | }
|
422 | 422 | else
|
423 | 423 | {
|
424 |
| - if ($Credential) |
| 424 | + if ($Credential) |
425 | 425 | {
|
426 | 426 | $ConnectionString = "Server={0};Database={1};User ID={2};Password=`"{3}`";Trusted_Connection=False;Connect Timeout={4};Encrypt={5}" -f $SQLInstance,$Database,$Credential.UserName,$Credential.GetNetworkCredential().Password,$ConnectionTimeout,$Encrypt
|
427 | 427 | }
|
428 |
| - else |
| 428 | + else |
429 | 429 | {
|
430 |
| - $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $SQLInstance,$Database,$ConnectionTimeout |
431 |
| - } |
432 |
| - |
| 430 | + $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2};Encrypt={3}" -f $SQLInstance,$Database,$ConnectionTimeout,$Encrypt |
| 431 | + } |
| 432 | + |
433 | 433 | $conn = New-Object System.Data.SqlClient.SQLConnection
|
434 |
| - $conn.ConnectionString = $ConnectionString |
| 434 | + $conn.ConnectionString = $ConnectionString |
435 | 435 | Write-Debug "ConnectionString $ConnectionString"
|
436 | 436 |
|
437 | 437 | Try
|
438 | 438 | {
|
439 |
| - $conn.Open() |
| 439 | + $conn.Open() |
440 | 440 | }
|
441 | 441 | Catch
|
442 | 442 | {
|
|
445 | 445 | }
|
446 | 446 | }
|
447 | 447 |
|
448 |
| - #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller |
449 |
| - if ($PSBoundParameters.Verbose) |
450 |
| - { |
451 |
| - $conn.FireInfoMessageEventOnUserErrors=$true |
452 |
| - $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] { Write-Verbose "$($_)" } |
453 |
| - $conn.add_InfoMessage($handler) |
| 448 | + #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller |
| 449 | + if ($PSBoundParameters.Verbose) |
| 450 | + { |
| 451 | + $conn.FireInfoMessageEventOnUserErrors=$true |
| 452 | + $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] { Write-Verbose "$($_)" } |
| 453 | + $conn.add_InfoMessage($handler) |
454 | 454 | }
|
455 |
| - |
456 |
| - $cmd = New-Object system.Data.SqlClient.SqlCommand($Query,$conn) |
| 455 | + |
| 456 | + $cmd = New-Object system.Data.SqlClient.SqlCommand($Query,$conn) |
457 | 457 | $cmd.CommandTimeout=$QueryTimeout
|
458 | 458 |
|
459 | 459 | if ($SqlParameters -ne $null)
|
|
466 | 466 | { $cmd.Parameters.AddWithValue($_.Key, [DBNull]::Value) }
|
467 | 467 | } > $null
|
468 | 468 | }
|
469 |
| - |
470 |
| - $ds = New-Object system.Data.DataSet |
471 |
| - $da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd) |
472 |
| - |
| 469 | + |
| 470 | + $ds = New-Object system.Data.DataSet |
| 471 | + $da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd) |
| 472 | + |
473 | 473 | Try
|
474 | 474 | {
|
475 | 475 | [void]$da.fill($ds)
|
|
479 | 479 | }
|
480 | 480 | }
|
481 | 481 | Catch
|
482 |
| - { |
| 482 | + { |
483 | 483 | $Err = $_
|
484 | 484 | if(-not $PSBoundParameters.ContainsKey('SQLConnection'))
|
485 | 485 | {
|
|
492 | 492 | 'Stop' { Throw $Err }
|
493 | 493 | 'Continue' { Write-Error $Err}
|
494 | 494 | Default { Write-Error $Err}
|
495 |
| - } |
| 495 | + } |
496 | 496 | }
|
497 | 497 |
|
498 | 498 | if($AppendServerInstance)
|
|
507 | 507 | }
|
508 | 508 | }
|
509 | 509 |
|
510 |
| - switch ($As) |
511 |
| - { |
512 |
| - 'DataSet' |
| 510 | + switch ($As) |
| 511 | + { |
| 512 | + 'DataSet' |
513 | 513 | {
|
514 | 514 | $ds
|
515 |
| - } |
| 515 | + } |
516 | 516 | 'DataTable'
|
517 | 517 | {
|
518 | 518 | $ds.Tables
|
519 |
| - } |
| 519 | + } |
520 | 520 | 'DataRow'
|
521 | 521 | {
|
522 | 522 | $ds.Tables[0]
|
|
0 commit comments