Powershell Get-Winevent未找到符合指定选择条件的事件

时间:2014-10-08 01:01:15

标签: powershell

我正在编写一个Powershell 2.0脚本,该脚本解析脱机.evtx事件日志的文件夹,并生成具有指定输出的csv。我只查找某些事件ID,我只是将某些字段输出到csv。当.evtx文件中不存在指定的事件ID时,我遇到的问题就出现了。它会产生一个错误:" Get-WinEvent:找不到符合指定选择标准的事件" (NoMatchingEventsFound)。这是有道理的,但是有没有办法以一种方式来编写它,而不是关心"如果事件ID存在并继续解析? (我只是在寻找这些所选ID的特定存在,如果它们不存在我也不在乎)这是我的代码:

 $ReviewFile = ("\\thepath\" + (Get-Date).tostring("dd-MMM-yy") + " Review.csv")
If (Test-Path $Reviewfile){Remove-Item $ReviewFile}
 $EventLogIDs = "4476","4741","4742" # etc...I have quite a number of IDs
 Get-WinEvent -FilterHashtable @{Path="\\evtxpath\" + (Get-Date).tostring("yyyyMMdd") + "\*Security*";id=@($EventLogIDs);}|
 Select-Object Id,LevelDisplayName,Message,MachineName,RecordId,TaskDisplayName | Export-CSV $ServerReviewFile

我试图添加-ErrorAction静默继续,但它会跳过整个哈希表。 我正在思考可能在循环中使用try和catch循环遍历eventID数组。那会有用吗?这将如何影响哈希表生成代码的语法?还有其他建议吗?谢谢你的建议

1 个答案:

答案 0 :(得分:0)

当然,你可以使用try catch:

$EventLogIDs = @("4476", "4741", "4742")

ForEach($EvtxFileInfo in (Get-ChildItem 'C:\EvtxFolder\'))
{
    $ReviewFile = ("\\ThePath\" + (Get-Date).tostring("dd-MMM-yy") +
        " Review.csv")

    if (Test-Path $ReviewFile) { Remove-Item $ReviewFile }

    try 
    {
        Get-WinEvent -FilterHashtable @{ 
                Path = $EvtxFileInfo.FullName;  # or your way
                Id = $EventLogIDs;
            } | 
            Select Id, LevelDisplayName, Message, MachineName, RecordId, TaskDisplayName | 
            Export-Csv $ReviewFile -NoTypeInfo
    }
    catch  # plain catch = catch everything
    {
        # do nothing
    }
}

有关详细信息:ForEach
有关更多信息:Try Catch (Finally)
参考:Get-ChildItem