rightclickscript
rightclickscript

Reputation: 63

How do I suppress PowerShell script block errors?

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.

Upvotes: 1

Views: 981

Answers (1)

Alexander Obersht
Alexander Obersht

Reputation: 3275

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"
}

Upvotes: 1

Related Questions