Skip to content

Commit 448df94

Browse files
committed
Fix for -Encrypt switch when credentials are not passed
1 parent 718ecdf commit 448df94

File tree

2 files changed

+116
-116
lines changed

2 files changed

+116
-116
lines changed

Invoke-Sqlcmd2.ps1

Lines changed: 92 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
function Invoke-Sqlcmd2
1+
function Invoke-Sqlcmd2
22
{
3-
<#
4-
.SYNOPSIS
5-
Runs a T-SQL script.
3+
<#
4+
.SYNOPSIS
5+
Runs a T-SQL script.
66
7-
.DESCRIPTION
7+
.DESCRIPTION
88
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.
1010
1111
Help details below borrowed from Invoke-Sqlcmd
1212
@@ -26,9 +26,9 @@
2626
2727
.PARAMETER Credential
2828
Specifies A PSCredential for SQL Server Authentication connection to an instance of the Database Engine.
29-
29+
3030
If -Credential is not specified, Invoke-Sqlcmd attempts a Windows Authentication connection using the Windows account running the PowerShell session.
31-
31+
3232
SECURITY NOTE: If you use the -Debug switch, the connectionstring including plain text password will be sent to the debug stream.
3333
3434
.PARAMETER Encrypt
@@ -41,7 +41,7 @@
4141
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.
4242
4343
.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
4545
4646
PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/
4747
@@ -59,9 +59,9 @@
5959
If specified, use an existing SQLConnection.
6060
We attempt to open this connection if it is closed
6161
62-
.INPUTS
63-
None
64-
You cannot pipe objects to Invoke-Sqlcmd2
62+
.INPUTS
63+
None
64+
You cannot pipe objects to Invoke-Sqlcmd2
6565
6666
.OUTPUTS
6767
As PSObject: System.Management.Automation.PSCustomObject
@@ -70,31 +70,31 @@
7070
As DataSet: System.Data.DataTableCollectionSystem.Data.DataSet
7171
As SingleValue: Dependent on data type in first column.
7272
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
8080
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.
8585
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
8888
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
9191
9292
.EXAMPLE
9393
Invoke-Sqlcmd2 -ServerInstance MyServer\MyInstance -Query "SELECT ServerName, VCNumCPU FROM tblServerInfo" -as PSObject | ?{$_.VCNumCPU -gt 8}
9494
Invoke-Sqlcmd2 -ServerInstance MyServer\MyInstance -Query "SELECT ServerName, VCNumCPU FROM tblServerInfo" -as PSObject | ?{$_.VCNumCPU}
9595
9696
This example uses the PSObject output type to allow more flexibility when working with results.
97-
97+
9898
If we used DataRow rather than PSObject, we would see the following behavior:
9999
Each row where VCNumCPU does not exist would produce an error in the first example
100100
Results would include rows where VCNumCPU has DBNull value in the second example
@@ -103,52 +103,52 @@
103103
'Instance1', 'Server1/Instance1', 'Server2' | Invoke-Sqlcmd2 -query "Sp_databases" -as psobject -AppendServerInstance
104104
105105
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
112112
tempdb 563200 Server1/Instance1
113-
...
114-
OperationsManager 20480000 Server2
113+
...
114+
OperationsManager 20480000 Server2
115115
116116
.EXAMPLE
117117
#Construct a query using SQL parameters
118118
$Query = "SELECT ServerName, VCServerClass, VCServerContact FROM tblServerInfo WHERE VCServerContact LIKE @VCServerContact AND VCServerClass LIKE @VCServerClass"
119119
120120
#Run the query, specifying values for SQL parameters
121121
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
128128
129129
.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+
132132
This example uses an existing SQLConnection and runs a basic T-SQL query against it
133133
134-
StartTime
135-
-----------
136-
2010-08-12 21:21:03.593
134+
StartTime
135+
-----------
136+
2010-08-12 21:21:03.593
137137
138138
139-
.NOTES
140-
Version History
139+
.NOTES
140+
Version History
141141
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
146146
v1.4 - Justin Dearing <zippy1981 _at_ gmail.com> - Added the ability to pass parameters to the query.
147147
v1.4.1 - Paul Bryson <atamido _at_ gmail.com> - Added fix to check for null values in parameterized queries and replace with [DBNull]
148148
v1.5 - Joel Bennett - add SingleValue output option
149149
v1.5.1 - RamblingCookieMonster - Added ParameterSets, set Query and InputFile to mandatory
150150
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+
152152
github.com - https://github.com/RamblingCookieMonster/PowerShell
153153
v1.5.3 - RamblingCookieMonster - Replaced DBNullToNull param with PSObject Output option. Added credential support. Added pipeline support for ServerInstance. Added to GitHub
154154
- Added AppendServerInstance switch.
@@ -202,7 +202,7 @@
202202
ValueFromRemainingArguments=$false)]
203203
[string]
204204
$Database,
205-
205+
206206
[Parameter( ParameterSetName='Ins-Que',
207207
Position=2,
208208
Mandatory=$true,
@@ -215,7 +215,7 @@
215215
ValueFromRemainingArguments=$false )]
216216
[string]
217217
$Query,
218-
218+
219219
[Parameter( ParameterSetName='Ins-Fil',
220220
Position=2,
221221
Mandatory=$true,
@@ -229,7 +229,7 @@
229229
[ValidateScript({ Test-Path $_ })]
230230
[string]
231231
$InputFile,
232-
232+
233233
[Parameter( ParameterSetName='Ins-Que',
234234
Position=3,
235235
Mandatory=$false,
@@ -251,7 +251,7 @@
251251
Position=4,
252252
Mandatory=$false,
253253
ValueFromRemainingArguments=$false)]
254-
[switch]
254+
[switch]
255255
$Encrypt,
256256

257257
[Parameter( Position=5,
@@ -260,7 +260,7 @@
260260
ValueFromRemainingArguments=$false )]
261261
[Int32]
262262
$QueryTimeout=600,
263-
263+
264264
[Parameter( ParameterSetName='Ins-Fil',
265265
Position=6,
266266
Mandatory=$false,
@@ -273,15 +273,15 @@
273273
ValueFromRemainingArguments=$false )]
274274
[Int32]
275275
$ConnectionTimeout=15,
276-
276+
277277
[Parameter( Position=7,
278278
Mandatory=$false,
279279
ValueFromPipelineByPropertyName=$true,
280280
ValueFromRemainingArguments=$false )]
281281
[ValidateSet("DataSet", "DataTable", "DataRow","PSObject","SingleValue")]
282282
[string]
283283
$As="DataRow",
284-
284+
285285
[Parameter( Position=8,
286286
Mandatory=$false,
287287
ValueFromPipelineByPropertyName=$true,
@@ -310,14 +310,14 @@
310310
[ValidateNotNullOrEmpty()]
311311
[System.Data.SqlClient.SQLConnection]
312312
$SQLConnection
313-
)
313+
)
314314

315315
Begin
316316
{
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")
321321
}
322322

323323
Write-Verbose "Running Invoke-Sqlcmd2 with ParameterSet '$($PSCmdlet.ParameterSetName)'. Performing query '$Query'"
@@ -421,22 +421,22 @@
421421
}
422422
else
423423
{
424-
if ($Credential)
424+
if ($Credential)
425425
{
426426
$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
427427
}
428-
else
428+
else
429429
{
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+
433433
$conn = New-Object System.Data.SqlClient.SQLConnection
434-
$conn.ConnectionString = $ConnectionString
434+
$conn.ConnectionString = $ConnectionString
435435
Write-Debug "ConnectionString $ConnectionString"
436436

437437
Try
438438
{
439-
$conn.Open()
439+
$conn.Open()
440440
}
441441
Catch
442442
{
@@ -445,15 +445,15 @@
445445
}
446446
}
447447

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)
454454
}
455-
456-
$cmd = New-Object system.Data.SqlClient.SqlCommand($Query,$conn)
455+
456+
$cmd = New-Object system.Data.SqlClient.SqlCommand($Query,$conn)
457457
$cmd.CommandTimeout=$QueryTimeout
458458

459459
if ($SqlParameters -ne $null)
@@ -466,10 +466,10 @@
466466
{ $cmd.Parameters.AddWithValue($_.Key, [DBNull]::Value) }
467467
} > $null
468468
}
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+
473473
Try
474474
{
475475
[void]$da.fill($ds)
@@ -479,7 +479,7 @@
479479
}
480480
}
481481
Catch
482-
{
482+
{
483483
$Err = $_
484484
if(-not $PSBoundParameters.ContainsKey('SQLConnection'))
485485
{
@@ -492,7 +492,7 @@
492492
'Stop' { Throw $Err }
493493
'Continue' { Write-Error $Err}
494494
Default { Write-Error $Err}
495-
}
495+
}
496496
}
497497

498498
if($AppendServerInstance)
@@ -507,16 +507,16 @@
507507
}
508508
}
509509

510-
switch ($As)
511-
{
512-
'DataSet'
510+
switch ($As)
511+
{
512+
'DataSet'
513513
{
514514
$ds
515-
}
515+
}
516516
'DataTable'
517517
{
518518
$ds.Tables
519-
}
519+
}
520520
'DataRow'
521521
{
522522
$ds.Tables[0]

0 commit comments

Comments
 (0)