Search code examples
powershellpowershell-4.0

Loop through several text files with a multiple line regex in PowerShell


I'm trying to seach through several textfiles with a regex. I've managed to get it working when the regex matches on a single row but when I test with a regex that match on one row and end of another row, it doesn't work.

I've read that you first need to read the entire file to a variable/array and then do the regex search. I've not managed to get this to work.

The structure of the folders and files are

Root Folder
├─17-11-01
│ ├─trace-0.log
│ └─trace-1.log
└─17-11-02
  ├─trace-0.log
  └─trace-1.log

I have managed to get the full path to the files but I'm not sure how I read the content of the file. I found [IO.File]::ReadAllText($Path) but am not sure how I add it to the command below.

Get-ChildItem $Path -Filter $Filter -Recurse |
    Select FullName |
    ft -HideTableHeaders

To summarize what I'm trying to do.

  • Do a regex search where the matched text will span multiple lines.
  • Multiple files in multiple paths under the same root.
  • Count each of the regex matches.

I'm currently using PowerShell v2 on Windows 7 but I can upgrade to v4. The script will mostly be used on Windows 10 and Windows Server 2012 R2 and later.

Edit 1 Here is an example of the log file and the regex.

FINER: Entering service: ABC  
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: The request has been completed.
(2017-10-.*FINER\: Entering service: (ABC |ABC1|ABC2))[\s\S]*?(INFO: \d\d\d\d\d\d\d\d\d\d\d\d The request has been completed)

Solution

  • Edit 2 Solution

    Here is the final code. The regex is in my example didn't match the the example log.

    $Files = (Get-ChildItem $Path -Filter $FilterFile -Recurse | Get-Content | Out-String)
    
    (Select-String -inputObject $Files -pattern $Regex -AllMatches).Matches.Count
    

    The expression worked just fine, that was not the issue.

    Thanks!