我正在尝试使用Powershell监视日志文件,但是我无法弄清楚应该使用什么正则表达式来获得所需的监视输出。
Get-Content $file -wait | where {$_ -match "some regex"} |
foreach { send_email($_) }
这是我的日志文件的示例。
19:43:06.5230 Info {"message":"YourCode_Prod execution started","level":"Information","timeStamp":"2019-01-15T19:43:06.5132404+00:00","fingerprint":"588aeb19-76e5-415a-88ff-a69797eb414f","windowsIdentity":"AD\\gaurav.m","machineName":"EDEV-3","processName":"YourCode_Prod","processVersion":"1.0.6800.16654","fileName":"YourCode_Work","jobId":"22a537ae-35e6-4abd-a57d-9dd0c273e81a","robotName":"Gaurav"} 19:50:48.8014 Info {"message":"YourCode_Prod execution ended","level":"Information","timeStamp":"2019-01-15T19:50:48.8005228+00:00","fingerprint":"b12b7d6f-cf3a-4e24-b1e6-1cf4413c12e2","windowsIdentity":"AD\\gaurav.m","machineName":"EDEV-3","processName":"YourCode_Prod","processVersion":"1.0.6800.16654","fileName":"YourCode_Work","jobId":"22a537ae-35e6-4abd-a57d-9dd0c273e81a","robotName":"Gaurav","totalExecutionTimeInSeconds":462,"totalExecutionTime":"00:07:42"}
我试图生成正则表达式,但是我找不到正确的逻辑。
$searchpattern = [regex]"(?:(?:started))|(?:(?:ended))"
Get-Content -Path C:\Execution.log | foreach {
if ($PSItem -match $searchpattern) {
# does the entry have a valid date/time
$time, $type, $data = $PSItem -split " ", 3
$time
$type
$data
}
}
我需要监视此文件,该文件将有很多行,但是我只想对“执行开始”和“执行结束”采取措施。
我可以将消息时间的类型和数据分开。但是我需要进一步深入数据。
此脚本每5分钟运行一次,因此我将比较-5分钟的时间并从那里开始读取日志,一旦发现结束或开始,我将采取必要的措施。
答案 0 :(得分:2)
您的日志数据为JSON格式,因此您可以像这样简单地处理提取的数据。
Get-Content -Path C:\Execution.log | ForEach-Object {
$time, $type, $json = $_ -split " ", 3
$data = ConvertFrom-Json $json
if ($data.message -match 'execution (started|ended)') {
# do stuff
}
}