我正在尝试从日志文件中提取由两件事定义的错误行。日志文件行如下所示:
2018-05-22 06:25:35.309 +0200 (Production,S8320,DKMdczmpOXVJtYCSosPS6SfK8kGTSN1E,WwObvwqUw-0AAEnc-XsAAAPR) catalina-exec-12 : ERROR com.tableausoftware.api.webclient.remoting.RemoteCallHandler - Exception raised by call target: User 2027 does not have permissions to view comments for view 13086. (errorCode=1) com.tableausoftware.domain.exceptions.PermissionDeniedException: User 2027 does not have permissions to view comments for view 13086. (errorCode=1)
错误在两行中描述,因此我需要过滤错误和当前小时,然后将其复制到文件中。 此代码确实会复制所有错误,但不仅仅是当前小时。
$hodina = (Get-Date -UFormat "%H").ToString()
$hodina = " " + $hodina +":"
$err = ": ERROR"
$errors = Select-String -Path "D:\..\file.log" -Pattern $hodina, $err -Context 0, 1
echo ($errors).Line >> Errors_file.txt
所以我想知道如何将多个变量放入-Pattern
,或者是否有另一个解决此问题的方法。
答案 0 :(得分:0)
以下是获取所有匹配行的方法:
Get-Content "file.log" |
Select-String -Pattern "^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})).* : ERROR (?:(.*))$" |
ForEach-Object {
[PsCustomObject]@{
TimeStamp=(Get-Date $_.Matches.Groups[1].Value)
LineNumber=$_.LineNumber
Error=$_.Matches.Groups[2].Value
}
}
这将为您提供如下输出:
TimeStamp LineNumber Error
--------- ---------- -----
22/05/2018 06:25:35 1 com.tableausoftware.api.webclient.remoting.RemoteCallHandler - Exception raised...
22/05/2018 06:25:35 4 com.tableausoftware.api.webclient.remoting.RemoteCallHandler - Exception raised...
22/05/2018 06:25:35 8 com.tableausoftware.api.webclient.remoting.RemoteCallHandler - Exception raised...
22/05/2018 06:25:35 10 com.tableausoftware.api.webclient.remoting.RemoteCallHandler - Exception raised...
如果您只想要时间戳小时与当前小时匹配的项目,请修改如下代码:
Get-Content "file.log" |
Select-String -Pattern "^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})).* : ERROR (?:(.*))$" |
ForEach-Object {
[PsCustomObject]@{
TimeStamp=(Get-Date $_.Matches.Groups[1].Value)
LineNumber=$_.LineNumber
Error=$_.Matches.Groups[2].Value
}
} | Where-Object {$_.TimeStamp.Hour -eq (Get-Date).Hour}
然后您可以将输出发送到文件,或者更好(如果您计划稍后在PowerShell中操作它们),CSV(Export-Csv
)或CliXml(Export-CliXml
)