下面的Powershell脚本效果很好。它进入我的eventviewer日志,捕获过去24小时内特定eventid的所有事件,并将其导出到临时文件。我现在正在尝试修改此脚本,以便仅显示以下日期范围(2020年1月7日至2020年2月6日)中的数据。对于我的一生,我无法弄清楚。有人知道如何添加日期范围吗?
Get-WinEvent -ProviderName $ProviderName -MaxEvents 64000 -EA SilentlyContinue | Where-Object
$_.id -in $EventID -and $_.Timecreated -gt (Get-date).AddHours(-24)
} | Sort TimeCreated -Descending | Export-Csv $Path -NoTypeInformation
由于您正在使用$_.id -in $EventID
,所以我收集到变量$EventID
是事件ID的数组。如果不是,并且这是单个事件ID,则将-in
更改为-eq
。
要获得某个范围内的创建日期,可以执行:
$startDate = (Get-Date -Year 2020 -Month 1 -Day 7).Date # .Date makes it midnight
$endDate = (Get-Date -Year 2020 -Month 2 -Day 6).Date
Get-WinEvent -ProviderName $ProviderName -MaxEvents 64000 -ErrorAction SilentlyContinue |
Where-Object { $_.id -in $EventID -and $_.Timecreated -ge $startDate -and $_.Timecreated -le $endDate } |
Sort-Object TimeCreated -Descending | Export-Csv $Path -NoTypeInformation
这将在开始日期和结束日期之间进行过滤。如果您不想这样做,请将-ge
更改为-gt
,然后将-le
更改为lt
在Where-Object
子句中,您需要检查$_.TimeCreated
是否同时大于Jan. 7, 2020 12:00:00 AM
和小于Feb. 6, 2020 11:59:59 PM
:
$startTime = Get-Date -Date "Jan. 7, 2020 12:00:00 AM"
$endTime = Get-Date -Date "Feb. 6, 2020 11:59:59 PM"
Get-WinEvent .... | Where-Object {
$_.id -eq $EventID -and $_.TimeCreated -ge $startTime -and $_.TimeCreated -le $endTime
}
之所以有效,是因为虽然Get-Date -Date
需要一个DateTime
对象,但是PowerShell知道如何将正确格式化的日期字符串隐式转换为DateTime
对象。然后,您只需要确保每个事件的TimeCreated
属性都在上下限之间即可。
请参阅本文,了解有关PowerShell "Type Conversion Magic"的工作方式的更多信息。
您可以使用builltin过滤器来执行此操作,它将更快。要超过日志名的256个限制,请使用foreach循环。超过846个提供者名称相同。
get-winevent @{ providername = 'esent'; id = 916;
starttime = '1/7'; endtime = '2/6' } -MaxEvents 3
ProviderName: ESENT
TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------
2/5/2020 11:09:00 PM 916 Information svchost (3120,G,0) The beta feature EseDiskFlushConsistency is enabled in ESENT due to the beta site mode settings 0x800000.
2/5/2020 10:08:59 PM 916 Information svchost (3120,G,0) The beta feature EseDiskFlushConsistency is enabled in ESENT due to the beta site mode settings 0x800000.
2/5/2020 9:08:00 PM 916 Information svchost (3120,G,0) The beta feature EseDiskFlushConsistency is enabled in ESENT due to the beta site mode settings 0x800000.