Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify whether the SQL server instance is correct or not using powershell?

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?

like image 694
Samselvaprabu Avatar asked Apr 12 '26 06:04

Samselvaprabu


2 Answers

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"
}
like image 161
David Brabant Avatar answered Apr 13 '26 23:04

David Brabant


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
{
   $_
}
like image 36
Shay Levy Avatar answered Apr 14 '26 01:04

Shay Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!