下面是一个简单的脚本块,脚本块工作。但是,我想抑制脚本块将生成的任何错误。
$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”参数调用“打开”的异常:“错误[IM002] [Microsoft] [ODBC驱动程序管理器]未找到数据源名称且未指定默认驱动程序” + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:OdbcException + PSComputerName:localhost
如果我输入out-null
我的$test
变量为空。当我使用有效的DSN名称时,一切都按预期工作。
答案 0 :(得分: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"
}