2015-10-04 54 views
1

下面是一个简单的脚本块,脚本块的作品。但是,我想要禁止脚本块会产生的任何错误。如何禁止PowerShell脚本块错误?

$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 

我想摆脱这是一个简单的测试32位ODBC连接。如果连接失败,连接状态将保持关闭,但我也得到一个异常的错误,我想打压

异常调用“打开”和“0”的说法(S):“ERROR [IM002] [微软] [ODBC驱动程序管理器]数据源名称未找到和指定” + CategoryInfo默认驱动程序:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:OdbcException + PSComputerName:本地主机

如果我管out-null我的$test变量是空的。当我使用有效的DSN名称时,所有内容都可以按需使用。

+0

尝试增加'-ErrorAction SilentlyContinue' – user4317867

+0

......和OP学不会错误处理。这对我来说是一个不好的建议。隐藏错误并不是一个好时尚。 – sodawillow

回答

1

你可以使用在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" 
}