Powershell try catch invoke-sqlcmd

标签 powershell try-catch try-catch-finally

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

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 : 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时出错”

最佳答案

似乎错误被认为是非终止的,这有点奇怪。尝试使用带有附加参数-ErrorAction Stop的Invoke-SqlCommand。如果错误是非终止错误,它将把它转换为您可以捕获的终止错误。

关于Powershell try catch invoke-sqlcmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13610593/

相关文章:

powershell - 如何获取远程计算机的磁盘容量和可用空间

python - 在Windows中使用python获取重启历史记录

powershell - 从 Visual Studio Code 更改 powershell 中的当前工作目录

python - try except 在一个 while 循环中

c# - 如何获取导致异常的方法的名称

java - 为什么Java不支持在finally抛出异常时从try/catch lost中检索异常?

iis - 使用Powershell为IIS虚拟目录设置 “Allow clients to upload files”

java - 强制 try block 在两者之间中断的最佳方法是什么?

python - 仅在引发异常时清理对象

c#-4.0 - 为什么我的 "finally"不运行?