1

Below is a simple script block, the script block works. However, I would like to suppress any errors that the script block would generate.

$Name = 'TEST'
$SB = { param ($DSNName) ;
    $conn = new-object system.data.odbc.odbcconnection  
    $conn.ConnectionString = ('DSN='+ $DSNName) 
    $conn.open() 
    $ConState = $conn.State
    $conn.Close() 
    $ConState
}
$test = Start-job -scriptblock $SB -args $Name -RunAs32 -ErrorAction Stop | wait-job | receive-job

What I am trying to get out of this is a simple test for a 32bit ODBC connection. If the connection fails the connection state will remain closed but I also get an exception error I would like to suppress

Exception calling "Open" with "0" argument(s): "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : OdbcException + PSComputerName : localhost

If I pipe to out-null my $test variable is empty. When I use a valid DSN Name everything works as desired.

2
  • Try adding -erroraction SilentlyContinue Commented Oct 5, 2015 at 1:28
  • ... and OP will never learn error handling. This is a poor suggestion to me. Hiding errors is not a good fashion. Commented Oct 5, 2015 at 17:24

1 Answer 1

1

You could use try..catch:

try {
    $test = Start-job -scriptblock $SB -args $Name -RunAs32 -ErrorAction Stop | wait-job | receive-job
catch [System.Management.Automation.MethodInvocationException] {
    # Do nothing here if you want to suppress the exception completely.
    # Although redirecting it to a log file may be a better idea, e.g.
    # $Error[0] | Out-File -FilePath "script.log"
}
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.