簡體   English   中英

選擇字符串多個變量模式

[英]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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM