gpt4 book ai didi

sql-server - 如何使用powershell验证SQL server实例是否正确?

转载 作者:行者123 更新时间:2023-12-03 11:19:45 25 4
gpt4 key购买 nike

我们使用 Invoke-sqlcmd cmdlet 通过 powershell 执行 SQL 查询。

如果 SQl 服务器实例被指定为错误,则会抛出异常。

虽然我已经在 try catch 中捕获了错误,但它仍然在控制台中抛出异常

"Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server"

            try {
$Qresult= Invoke-sqlcmd -query $SelectQuery -ServerInstance $srvInstance
$Qresult = $Qresult| % { $_.$columnName+"`n" }
LogWrite "$Qresult`n"
}
catch {
Write-error "Error occured when executing sql $SelectQuery"
LogWrite $Error[0]
}

如何在执行任何查询之前验证 SQL Server 实例是否可用并且正在运行?

最佳答案

function SQL-Ping-Instance 
{
param (
[parameter(Mandatory = $true)][string] $ServerInstance,
[parameter(Mandatory = $false)][int] $TimeOut = 1
)

$PingResult = $false

try
{
$SqlCatalog = "master"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $ServerInstance; Database = $SqlCatalog; Integrated Security = True; Connection Timeout=$TimeOut"
$SqlConnection.Open()
$PingResult = $SqlConnection.State -eq "Open"
}

catch
{
}

finally
{
$SqlConnection.Close()
}

return $pingResult
}

if (SQL-Ping-Instance $srvInstance)
{
$Qresult= Invoke-sqlcmd -query $SelectQuery -ServerInstance $srvInstance
$Qresult = $Qresult| % { $_.$columnName+"`n" }
LogWrite "$Qresult`n"
}
else
{
LogWrite "Couldn't contact $srvInstance"
}

关于sql-server - 如何使用powershell验证SQL server实例是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540445/

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