How to use Powershell to filter out multi-lines group of text from a file?

2

I have an error log that I would like to filter out all the known errors using Powershell. I know how to filter by line in powershell, but my problem is that the errors in the error log span multiple lines, but they always start with a date time. Eg:

2016-01-14 01:01:01 Error 1: blab blab blab
blab blab blab line 1
blab blab blab line 2
blab blab blab line 3
2016-01-14 02:33:04 Error 2: blab blab blab
blab blab blab line 1
blab blab blab line 2
2016-01-14 02:33:04 Error 3: blab blab blab
blab blab blab line 1

and I wanted to filter out Error 1 and Error3, so the output will only be:

2016-01-14 02:33:04 Error 2: blab blab blab
blab blab blab line 1
blab blab blab line 2

Is there some way easy to group (by the date time) and filter them using powershell?

Thanks in advance!

Spock

Posted 2016-01-14T17:36:15.013

Reputation: 191

Answers

0

You could use something like this. This could be used to filter out a specific kind of error on multiple lines, in this example "Error 1". After that you can run again and filter out "Error 3".

$content = Get-Content -Path 'C:\Temp\test.log'

# Search all the errors
$errorLines = ($content | Select-String 'Error').LineNumber

foreach ($errorLine in $errorLines) {

    $someError = $content[$errorLine-1]

    # Known error to 'filter' out
    if ( $someError -like '*Error 1*') {

       # Search for line number of next error 
       [int]$errorLineNext = ($content[($errorLine)..$content.Count] | Select-String 'Error' | Select-Object -First 1).LineNumber

       # No next errors found? Then use the total line number
       if ( $errorLineNext -eq 0 ) { $errorLineNext = ($content.Count+1) - $errorLine }

       $content.RemoveRange($errorLine-1, $errorLineNext)  
    }
}

$content | Set-Content -Path 'C:\Temp\test.log'

Tim van Lint

Posted 2016-01-14T17:36:15.013

Reputation: 1