从事件日志中获取独特的事件及其计数

我有一个工作脚本,能够提取Windows应用程序,安全,设置和系统日志的报告,只显示过去30天内的关键和错误事件。 不过,我也希望脚本能够统计过去30天内发生的每个关键或错误事件的发生次数。 这是工作命令:

Get-EventLog Application -ComputerName $server -After $starttime | ? { $_.entryType -Match "Error" -and "Critical" } | Sort-Object EventID -Unique | Select-Object TimeGenerated,EventID,Source,Message | ft -AutoSize -Wrap | Out-File $file -Append 

以下是文本文件中的输出示例:

 TimeGenerated EventID Source Message ------------- ------- ------ ------- 7/8/2016 1:23:20 PM 0 SQL Server Report Service Service cannot be started. Microsoft.ReportingS ervices.Diagnostics.Utilities.InternalCatalogEx ception: An internal error occurred on the repo rt server. See the error log for more details. at Microsoft.ReportingServices.Library.Nativ e.GetSid(String name, Int32& length) at Microsoft.ReportingServices.Library.Nativ e.NameToSid(String name) at Microsoft.ReportingServices.Library.Servi ceAppDomainController.StartRPCServer(Boolean fi rstTime) at Microsoft.ReportingServices.Library.Servi ceAppDomainController.Start(Boolean firstTime) at Microsoft.ReportingServices.NTService.Rep ortService.OnStart(String[] args) at System.ServiceProcess.ServiceBase.Service QueuedMainCallback(Object state) 7/8/2016 1:23:20 PM 121 Report Server Windows Service (MSSQLSERVER) The Remote Procedure Call (RPC) service failed to start. 

如果在结果中有另一列显示每个EventID在指定时间段内的出现,那将是非常好的。

你可以这样做(第3和第4行是新的,并在Select-Object Count
从技术上讲,你也可以将Sort-Object中的-Unique从分组中移除,并且只传递组中的第一项或多或少相同。

 Get-EventLog Application -ComputerName $server -After $starttime | ? { $_.entryType -Match "Error" -and "Critical" } | Group-Object -Property EventID | % { $_.Group[0] | Add-Member -PassThru -NotePropertyName Count -NotePropertyValue $_.Count } | Sort-Object EventID -Unique | Select-Object Count, TimeGenerated, EventID, Source, Message | ft -AutoSize -Wrap | Out-File $file -Append