Select-字符串多变量模式

Select-string multiple variable patterns

我正在尝试从由两件事定义的日志文件中提取错误行。日志文件行如下所示:

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,或者是否有其他解决方案。

以下是获取所有匹配行的方法:

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)