gpt4 book ai didi

Powershell try catch invoke-sqlcmd

转载 作者:行者123 更新时间:2023-12-04 05:54:26 24 4
gpt4 key购买 nike

当使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com