We are using Invoke-sqlcmd cmdlet to execute SQL query using powershell.
If SQl server instance is given as wrong it is throwing exception.
Though i have captured the error in try catch still it throw exception in console as
"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]
}
How to verify whether SQL server instance is available and it is running before executing any query?
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"
}
Non terminating errors cannot be captured with try/catch. In order to make the error a terminating error, set the ErrorAction value to 'Stop'. If it doesn't help, try to add the -AbortOnError switch
try
{
Invoke-sqlcmd -query... -ErrorAction Stop
}
catch
{
$_
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With