capture invalid connection

  • Hi How to capture invalid connection with powershell?

    $conn = "MyServer\InstanceThatDoesNotExist"

    try {

    $serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server ($conn) ;

    $serverInstance.Databases.Count;

    }

    catch {

    $err = $Error[0].Exception ;

    write-host "Error caught: " $err.Message ;

    continue ;

    } ;

    I want to capture standard error

    "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured "

  • If you change your "catch" to a "catch [<ExceptionType>]" (e.g. "catch [System.Net.WebException]") or the correct type then you will be able to handle it gracefully.

    NOTE: I cannot remember the specific exception thrown that you need to catch.

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

  • could not find how to use " catch [<ExceptionType>]" in my case ,if you have example please post it

    found a workaround at https://ask.sqlservercentral.com/questions/119695/powershell-smo-is-not-working-for-non-admin-user.html (see block 35.)

    in my code I replaced with

    try {

    $serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server ($conn) ;

    write-host "Testing Connection with server:" $server

    # if we don't have connection this will throw exception

    write-host $serverInstance.Databases

    }

    catch {

    $err = $Error[0].Exception ;

    write-host "Error caught: " $err.Message ;

    continue ;

    } ;

  • It requires PowerShell 2.0 or above.

    Maybe this will help: http://stackoverflow.com/questions/2182666/powershell-2-0-try-catch-how-to-access-the-exception

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply