Skip to content

Commit 7d136b1

Browse files
committed
1.6.2 change
Fixed the .DESCRIPTION. Fixed the non SQL error handling and added Finally Block to close connection.
1 parent 4653b5e commit 7d136b1

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

Invoke-Sqlcmd2.ps1

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
Runs a T-SQL script.
66
77
.DESCRIPTION
8-
Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified.
8+
Runs a T-SQL script. Invoke-Sqlcmd2 runs the whole scipt and only captures the first selected result set, such as the output of PRINT statements when -verbose parameter is specified.
99
Paramaterized queries are supported.
1010
1111
Help details below borrowed from Invoke-Sqlcmd
@@ -158,6 +158,8 @@
158158
v1.6.0 - Added SQLConnection parameter and handling. Is there a more efficient way to handle the parameter sets?
159159
- Fixed SQLConnection handling so that it is not closed (we now only close connections we create)
160160
v1.6.1 - Shiyang Qiu - Fixed the verbose option and SQL error handling conflict
161+
v1.6.2 - Shiyang Qiu - Fixed the .DESCRIPTION.
162+
- Fixed the non SQL error handling and added Finally Block to close connection.
161163
162164
.LINK
163165
https://github.com/RamblingCookieMonster/PowerShell
@@ -474,29 +476,47 @@
474476
Try
475477
{
476478
[void]$da.fill($ds)
477-
if(-not $PSBoundParameters.ContainsKey('SQLConnection'))
478-
{
479-
$conn.Close()
480-
}
481479
}
482-
Catch [System.Data.SqlClient.SqlException]
480+
Catch [System.Data.SqlClient.SqlException] # For SQL exception
483481
{
484482
$Err = $_
485-
if(-not $PSBoundParameters.ContainsKey('SQLConnection'))
486-
{
487-
$conn.Close()
488-
}
483+
484+
Write-Verbose "Capture SQL Error"
489485

490486
if ($PSBoundParameters.Verbose) {Write-Verbose "SQL Error: $Err"} #Shiyang, add the verbose output of exception
491487

492488
switch ($ErrorActionPreference.tostring())
493489
{
494490
{'SilentlyContinue','Ignore' -contains $_} {}
495491
'Stop' { Throw $Err }
496-
'Continue' { Write-Error $Err}
497-
Default { Write-Error $Err}
492+
'Continue' { Throw $Err}
493+
Default { Throw $Err}
494+
}
495+
}
496+
Catch # For other exception
497+
{
498+
Write-Verbose "Capture Other Error"
499+
500+
$Err = $_
501+
502+
if ($PSBoundParameters.Verbose) {Write-Verbose "Other Error: $Err"}
503+
504+
switch ($ErrorActionPreference.tostring())
505+
{
506+
{'SilentlyContinue','Ignore' -contains $_} {}
507+
'Stop' { Throw $Err}
508+
'Continue' { Throw $Err}
509+
Default { Throw $Err}
498510
}
499511
}
512+
Finally
513+
{
514+
#Close the connection
515+
if(-not $PSBoundParameters.ContainsKey('SQLConnection'))
516+
{
517+
$conn.Close()
518+
}
519+
}
500520

501521
if($AppendServerInstance)
502522
{

0 commit comments

Comments
 (0)