powershell:如何通过invoke-sqlcmd捕获错误原因?

Dan*_* Wu 17 powershell try-catch

如果有什么不对的话我想抓住invoke-sql.但是当我运行以下命令时,如果$ sql无效,则无法捕获它.如何捕获此异常?

 try {
     Invoke-Sqlcmd -Query $sql -ServerInstance t1 -database db -QueryTimeout 65535 -ErrorAction 'Stop'
   } catch{
      "error when running sql $sql"
   }
Run Code Online (Sandbox Code Playgroud)

dje*_*eeg 27

我没有问题,使用名为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)
}
Run Code Online (Sandbox Code Playgroud)

和输出

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 '*'.
Run Code Online (Sandbox Code Playgroud)

您正在使用哪些输入参数,是使用PowerShell 1还是2?

  • `$ error`是当前运行空间中所有错误的列表.在catch块中你想使用`$ _`来查看当前错误. (8认同)
  • 我需要添加如果你不使用-ErrorAction stop而是使用Continue或SilentlyContinue,那么异常将不会被捕获。我的测试是PS V5.1和SQL Server 2016 (4认同)