2014-10-17 60 views
1

我正在寫一個簡單的腳本來解析某些事件日誌,但我需要沉默一些錯誤的時候,有沒有結果,或者如果實例id是無效的:追趕獲取,事件日誌錯誤

PS C:\> get-eventlog Application -instanceid 1111 

Get-EventLog : No matches found 
At line:1 char:13 
    + get-eventlog <<<< Application -instanceid 1111 
     + CategoryInfo   : ObjectNotFound: (:) [Get-EventLog], ArgumentException 
     + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand 

我能做到這一點,沉默,但是,這也將壓制其他錯誤:

PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch { } 

我試過,但它不工作:

PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] { } 

Unable to find type [ObjectNotFound]: make sure that the assembly containing this type is loaded. 
At line:1 char:91 
    + try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] <<<< { } 
    + CategoryInfo   : InvalidOperation: (ObjectNotFound:String) [], RuntimeException 
    + FullyQualifiedErrorId : TypeNotFound 

回答

2

可以使用-ErrorAction SilentlyContinue和後檢查你的$error變量替換爲「應用程序」發生了什麼它的價值[System.InvalidOperationException]

$error[0] 

,它會永遠包含最後一個錯誤對象。

2

絕不是唯一的選擇,但你可以嘗試這樣的事:

$result = get-eventlog Application -instanceid 1111 -erroraction silentlycontinue 
if($result){ 
    Write-Host "Found some." 
} else{ 
    Write-Host "wah wah wah waaaah... you know like the trombone sound" 
} 

我再一次不完全讀一個帖子。如果要對我的回答更好,我提供了這個可能有助於您try塊愁楚

try { 
    get-eventlog Application -instanceid 1111 -ErrorAction Stop 
} Catch [Exception]{ 
    $theError = $_ 
    Switch($theError .Exception.GetType().FullName){ 
     System.InvalidOperationException{Write-Host "This happened: $($theError.Exception.Message)"} 
     System.ArgumentException {Write-Host "This happened: $($theError.Exception.Message)"} 
     default{"Something else happened: $($theError.Exception.GetType().FullName)"} 
    } 
} 

使用-Stop創建終止錯誤。捕獲任何異常並將錯誤對象放入變量中,以便稍後在其他範圍內使用它。獲取異常名稱並在其上使用switch語句來確定適當的操作。在你找到「找不到匹配項」的情況下,你可以通過查看$_.Exception.GetType().FullName的值來看出[System.ArgumentException]。捕獲switch語句中的特定錯誤,並且如果您尚未捕獲到特定的異常,則可以在default中查看詳細信息。

因爲當我在cmdlet調用「Fizgig」

+0

問題是,我想其他錯誤顯示,例如,如果日誌文件是錯誤的或連接不能進行。我只是想沉默無效的實例id和空結果。 – Dendory 2014-10-18 00:04:43

0

你應該嘗試下面的語法讓你的錯誤,而不是停止執行腳本:

try 
    { 
     # check for eventLog 
     Get-EventLog -LogName "Application" -InstanceId 1111 -ErrorAction Stop 
    } 
    catch 
    { 
     # send error as ID 
     Write-Warning "Error -Message $($_.Exception.Message) -Line $($_.InvocationInfo.ScriptLineNumber) -Time $(Get-Date -Format 'HH.mm.ss.fff')" 
    }