powershell:如何通过 invoke-sqlcmd 捕获错误原因? [英] powershell:how to catch the error cause by invoke-sqlcmd?

查看:34
本文介绍了powershell:如何通过 invoke-sqlcmd 捕获错误原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有任何问题,我想捕获 invoke-sql.但是当我运行以下命令时,如果 $sql 无效,则无法捕获.如何捕捉这个异常?

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"
   }

推荐答案

我没有问题,使用名为 test.ps1 的脚本

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)
}

和输出

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 '*'.

您使用的是什么输入参数,您使用的是 powershell 1 还是 2?

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

这篇关于powershell:如何通过 invoke-sqlcmd 捕获错误原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆