【发布时间】:2019-10-23 04:44:20
【问题描述】:
我有一个(纯文本)日志文件,其中包含出现在大多数(但不是全部)文本行中的日期。日期并不总是出现在每一行的相同位置。尽管并非所有行都有日期,但在任何给定的 10 行中总是有一个日期。日志样本:
03/05/2019 Event A occurred
03/05/2019 Event B occurred
Event B Details: Details Details
03/07/2019 Event C occurred
Logging completed on 03/08/2019
03/08/2019 Event D occurred
我需要获取上次记录的日期。我不需要该行的内容,只需要该行中的日期。
#Get the log file. Tail it because it's huge. The regex pattern matches date format dd/mm/yyyy.
$log = (Get-Content -tail 10 C:\mylog.log | Select-String -Pattern "\d{2}/\d{2}\/d{4}"
#Get the last item in the $log variable. Convert it to a string.
$string = $log[-1].toString()
#Split the string. Match each element to a date format.
#When an element matches a date format, assign its value to a DateTime variable.
foreach ($s in $string.split() ){
if ($s -match "\d{2}/\d{2}\/d{4}"){
[DateTime]$date = $s
}
}
"The last entry in the log was made on $date"
这段代码的两部分(查找带有日期的最后一行,并从行中提取日期)看起来非常笨拙。有没有更好的方法来做到这一点?
【问题讨论】:
标签: powershell parsing