Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell:how to catch the error cause by invoke-sqlcmd?

I want to catch the invoke-sql if there is anything wrong. But when I run the following command, and if the $sql is invalid, it can't be caught. How to catch this exception?

 try {
     Invoke-Sqlcmd -Query $sql -ServerInstance t1 -database db -QueryTimeout 65535 -ErrorAction 'Stop'
   } catch{
      "error when running sql $sql"
   }
like image 378
Daniel Wu Avatar asked Jan 22 '11 04:01

Daniel Wu


People also ask

How do I catch an error in PowerShell?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

What does invoke-Sqlcmd do?

Description. The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.


1 Answers

I have no issue, using a script called test.ps1

add-pssnapin SqlServerCmdletSnapin100 get-host $sql = "selects * from syscomments" $server = "" $database = "" $username = "" $password = "" try {     Invoke-Sqlcmd -Query $sql -ServerInstance $server -database $database -QueryTimeout 65535 -ErrorAction 'Stop' -username $username -password $password } catch {   "error when running sql $sql"   Write-Host($error) } 

And the output

PS C:\> .\test.ps1 Name             : ConsoleHost Version          : 2.0 InstanceId       : 9ac019da-97bd-45d1-bfa5-65fb4d376dc6 UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture   : en-AU CurrentUICulture : en-US PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy IsRunspacePushed : False Runspace         : System.Management.Automation.Runspaces.LocalRunspace  error when running sql selects * from syscomments  Incorrect syntax near '*'. 

what input parameters are you using, are you using powershell 1 or 2?

like image 194
djeeg Avatar answered Sep 20 '22 01:09

djeeg