[英]Powershell Select-String how to filter by date?
I have a log file that starts with date format, I want to filter out lines that were added in the past 5min and work on them, but when I run my code it gives me wrong data我有一个以日期格式开头的日志文件,我想过滤掉过去 5 分钟内添加的行并处理它们,但是当我运行我的代码时,它给了我错误的数据
Log file Syntax日志文件语法
01/12/2020 00:00:00 log info
Code代码
$referenceTime = '{0:dd/MM/yyyy HH:mm:ss}' -f (Get-Date).AddMinutes(-5)
Get-Content -Path 'C:\..\data.log' |
Where-Object { (($_ -split '\s')[0] + " " + ($_ -split '\s')[1]) -gt $referenceTime } |
ForEach-Object {
#DO SOMETHING..
}
Dates should be compared to other dates, so you should not stringify them.日期应与其他日期进行比较,因此您不应将它们字符串化。
Try尝试
$referenceTime = (Get-Date).AddMinutes(-5)
Get-Content -Path 'C:\..\data.log' |
Where-Object { $_ -match '^(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2})' } |
Where-Object { [datetime]::ParseExact($matches[1], 'dd/MM/yyyy HH:mm:ss', $null) -gt $referenceTime } |
ForEach-Object {
$_
#DO SOMETHING.. For demo just output the line(s) that matched
}
The first Where-Object
matches any line that starts with what looks like a date in the given format and captures that part of the line in $matches[1]
.第一个
Where-Object
匹配以给定格式的日期开头的任何行,并在$matches[1]
中捕获该行的那一部分。
The second Where-Object
parses this matched date into a real [DateTime]
object, so you can compare it with the date in $referenceTime
第二个
Where-Object
将此匹配的日期解析为真正的[DateTime]
object,因此您可以将其与$referenceTime
中的日期进行比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.