Home > Software engineering >  Try/Catch in powershell running sql script
Try/Catch in powershell running sql script

Time:06-02

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

CodePudding user response:

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.

  • Related