1

I'm new to powershell and trying to use the try/catch command in handling the error message.

$Output = Invoke-SqlCmd -ServerInstance $dbinstance -username $dbusername -password $dbpassword -Database  $dbname -Query $Query

$isconnected = ''

if ($Output.uri -eq '0' ) {
$isconnected = $true
Write-Host -Foreground Green $isconnected

}else  {
$isconnected = $false
Write-Host -Foreground Red $isconnected
}

This is the error I get, but the result remains true even though the outcome should be error because I'm trying to figure out how to catch the error.

Error

1 Answer 1

4

If you want to implement a Try / Catch in your script you would need to put your code to query the Database inside the Try block and how you want to handle the error in the Catch block:

try {
    $param = @{
        ServerInstance = $dbinstance
        Username       = $dbusername
        Password       = $dbpassword
        Database       = $dbname
        Query          = $Query
    }
    $output = Invoke-SqlCmd @param -ErrorAction Stop
    Write-Host 'Connected' -Foreground Green
    # rest of your code goes here
}
catch {
    Write-Warning $_.Exception.Message
}

You might also benefit from Splatting.

$_ in the context of the Catch block represents the caught error, which is an instance of ErrorRecord. You might want to check the other properties aside from Exception.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.