如何使用 powershell 脚本在日志的最后 10 分钟内搜索模式 [英] How to search a pattern in last 10 minutes of log using a powershell script
问题描述
我正在尝试在 Powershell 中制作日志文件监视器.要求是使用 Powershell 在日志文件中搜索最近(最近 10 分钟日志打印)中的模式.日志文件格式如下:
I am trying to make a log file monitor in Powershell. The requirement is to search a pattern in most recent (last 10 minutes log prints) in a log file using Powershell. The format of log file is as follows:
20/04/2018 23:15:28: some information
20/04/2018 23:16:28: some information
20/04/2018 23:17:28: some information
:
20/04/2018 23:55:28: some information
20/04/2018 23:56:28: some information
例如,脚本在 23:58 运行,然后它应该只在20/04/2018 23:48"和20/04/2018 23:48"之间的日志打印中搜索模式.
So for example the script runs at 23:58 then it should search a pattern in log prints between '20/04/2018 23:48' and '20/04/2018 23:48' only.
请指教.谢谢
推荐答案
你总是可以从这样的文本文件中获取最后几个条目,比如 10 个:
You can always get the last few entries, say 10, from a text file like this:
Get-Content .\data.txt -Tail 10
当然,这可能不是最近 10 分钟的.这是一种选择:
Of course, this may not be from the last 10 minutes. Here is one option to do that:
Get-Content .\data.txt |
ForEach-Object {$threshold = (Get-Date).AddMinutes(-10)}{
if($_ -match "^(?<timestamp>(\d{2}/){2}\d{4} (\d{2}:){2}\d{2}):.*$")
{
if((Get-Date $Matches.timestamp) -gt $threshold)
{
$_
}
}
}
当然,模式匹配适用于 mm/dd/yyyy
和 dd/mm/yyyy
日期格式,因为结构相同.但是,如果文件使用与您的系统相反的方式,您可能会在 Get-Date
解析模式时遇到困难.例如,您示例中的格式在英国可以正常工作 (dd/mm/yyyy
),但在美国可能会失败 (mm/dd/yyyy
)- 我没有测试过,只是根据以前的日期问题发出警告.
Of course, the pattern match will work for both mm/dd/yyyy
and dd/mm/yyyy
date formats as the structure is the same. However, you may get difficulties with Get-Date
parsing the pattern if the file uses the opposite to your system. For example, the format in your example would work fine in the UK (dd/mm/yyyy
), but will likely fail in the USA (mm/dd/yyyy
) - I've not tested it, just warning based on previous issues with dates.
这篇关于如何使用 powershell 脚本在日志的最后 10 分钟内搜索模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!