2015-10-04 56 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" 
}