我是PowerShell的新手,需要一些关于greping和排序的帮助。我有很多包含以下格式的日志的日志文件:
2016-04-29T14:10:15,308000+0100; NOTICE ; Unknown HostId bla bla bla
我已经知道如何通过dir -r | select-string "bla" | ....
过滤特定的日志。但现在我想根据包含的时间戳排序找到的日志行。任何提示?
答案 0 :(得分:1)
您可以使用Sort-Object
按时间戳对行进行排序。
要正确排序,您需要先解析时间戳。由于时间戳中的皮秒,简单地转换为[datetime]
类型不会起作用,但我们可以使用DateTime.ParseExact():
$LogLines = Get-Content .\logfile.log
$LogLines | Sort-Object {
# Grab the timestamp, throw the rest away
$timestamp,$null = $_ -split ';',2
# Parse the timestamp, Sort-Object will use the emitted DateTime to sort
[datetime]::ParseExact($timestamp,'yyyy-MM-ddTHH:mm:ss,ffffffK',[cultureinfo]::InvariantCulture)
}