这是我获取特定时间事件日志的脚本。
$time = Get-WinEvent microsoft-windows-dns-client/operational -MaxEvents 1 |
Select-Object @{name="time"; expression={$_.timecreated.tostring("yyyy-MM-dd hh:mm:ss")}} |
Select-Object -ExpandProperty time
Get-WinEvent microsoft-windows-dns-client/operational |
Where-Object {$_.timecreated.tostring("yyyy-MM-dd hh:mm:ss") -eq "$time"}
如果我运行脚本,则显示结果。
脚本会在60秒或更长时间后退出。
我的错误是什么?
[第二个问题]
这是powershell的错误吗?
这种情况是在显示结果后脚本不会退出。
以下图片的结果需要3秒钟。
为什么这么慢?
powershell有关于时间条件的错误吗?
我认为解决了这个问题。谢谢gms0ulman。
while($true) {
$QUERY = @"
<QueryList><Query><Select Path='Microsoft-Windows-DNS-Client/Operational'>
*[System/EventID = 3006] and
*[System/TimeCreated[timediff(@SystemTime) <= 60000]] and
*[EventData/Data[@Name='QueryType'] != 28]
</Select></Query></QueryList>
"@
$CMD = (Get-WinEvent -FilterXml $QUERY).count 2>$null
if($CMD -ne 0) {
$LOG_LIST = Get-WinEvent -FilterXml $QUERY | Select-Object timecreated, processid, message | Sort-Object timecreated
foreach($LOG in $LOG_LIST) {
$TIMESTAMP = $LOG | Select-Object -ExpandProperty timecreated
$TIMESTAMP_SPLIT = $TIMESTAMP -split " "
$LOG_DATE = $TIMESTAMP_SPLIT[0]
$LOG_TIME = $TIMESTAMP_SPLIT[1]
$PROC_ID = $LOG | Select-Object -ExpandProperty processid
$PROC_NAME = Get-Process -id $PROC_ID | Select-Object -ExpandProperty processname
$MSG = $LOG | Select-Object -ExpandProperty message
$URL_1 = $MSG -replace '^\S{2}\s([^,]+).+','$1'
$URL_2 = $URL_1 -replace '^.*?([^.]+\.[^.]+\.?|[^.]+\.(ac|co|go|ne|nm|or|pe|re)\.[^.]+\.?)$','$1'
$LOG_SET = "$LOG_DATE`t$LOG_TIME`t$PROC_ID`t$PROC_NAME`t$URL_1`t$URL_2"
$LOG_SET >> C:\dns.csv
}
}
Start-Sleep 60
}
答案 0 :(得分:1)
我不认为$time
变量包含您期望的内容。在我的机器上,选择标准microsoft-windows-dns-client/operational
无效。
我相信这就是你所追求的:
# Get event based on your criteria. Implicitly converted to datetime data type
# You can check by running $time.GetType() or $time | gm
[datetime]$time = (Get-WinEvent microsoft-windows-dns-client/operational -MaxEvents 1).TimeCreated
# Get events where the TimeCreated field matches the previous time.
Get-WinEvent microsoft-windows-dns-client/operational | Where-Object {$_.TimeCreated -eq "$time"}
编辑 - 我错了,这不是你想要的
最初,我试图将EventLog限制在最后一天。然后是最后一分钟。但我仍然有你提到的滞后。
对我来说,解决方案是使用this article中所述的-FilterXML
参数。当然,需要自定义以指向PowerShell事件以满足您的需求
# xml source: https://blogs.msdn.microsoft.com/powershell/2011/04/14/using-get-winevent-filterxml-to-process-windows-events/
[xml]$filterXml = @"
<QueryList>
<Query Id="0" Path="Windows PowerShell">
<Select Path="Windows PowerShell">*[System[(Level=4 or Level=0)]]</Select>
</Query>
</QueryList>
"@
[datetime]$time = (Get-WinEvent -FilterXml $filterXml -MaxEvents 1).TimeCreated
Get-WinEvent -FilterXml $filterXml | Where-Object {$_.TimeCreated -eq $time}