Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

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"
   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:> .est.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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...