Search code examples
powershellsqlexception

Switching on SqlException.Number in Powershell


I have this catch block in my Powershell script.

catch [System.Data.SqlClient.SqlException]
{
   Write-Host "$_"
   Exit 2
}

I would really like to be able to switch on the error number. I know atleast in C# there's a property on the SqlException called number. Isn't that also true for Powershell?

If the property is there, how do I access it?

Thank you very much in advance


Solution

  • You should be able to access it in your catch block using:

    $_.Exception.Number
    

    i.e.

    catch [System.Data.SqlClient.SqlException]
    {
       Write-Host $_.Exception.Number
       Exit 2
    }