Powershell Try Catch invoke-sqlcmd [英] Powershell Try Catch invoke-sqlcmd

查看:41
本文介绍了Powershell Try Catch invoke-sqlcmd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 Invoke-Sqlcmd 连接到 SQL Server 失败时,我在 PowerShell 中捕获错误时遇到问题.这是一些用于演示问题的通用代码:

I am having problems catching an error in PowerShell when a connection fails to a SQL Server using Invoke-Sqlcmd. This is some generic code to demonstrate the issue:

CLS
$server = "Localhost\fake"
try
{
    Invoke-Sqlcmd -Query "SELECT DB_NAME() as [Database]" -Server $server
}
catch
{
    Write-Host "Error connecting to server " $server
}

我收到以下错误:

Invoke-Sqlcmd:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误.服务器未找到或无法访问.验证实例名称是正确的,并且 SQL Server 配置为允许远程连接.(提供程序:命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)

Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

我期待得到一行语句:连接到服务器Localhost\fake 时出错"

I was expecting to get the one line statement: "Error connecting to server Localhost\fake"

推荐答案

看起来错误被认为是非终止性的,这有点奇怪.尝试使用附加参数的 Invoke-SqlCommand:-ErrorAction Stop.如果存在非终止性错误,这会将其转换为您可以捕获的终止性错误.

It would appear that error is considered non-terminating which is a bit odd. Try the Invoke-SqlCommand with an additional parameter: -ErrorAction Stop. If there error is non-terminating, this will convert it to a terminating error that you can catch.

这篇关于Powershell Try Catch invoke-sqlcmd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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