gooly
gooly

Reputation: 1341

PowerShell: how to read a log-file as of a specific number within the lines?


I want to read a log file in each line is a sequence number. Now I'd like to get all lines that have seq.no. greater or equal than $low = 111 and less or eqal than $high = 123 - can I do that with a Where-Object:

 $LogEntries = Get-Content -Path $LogFile | Where-Object {
        $f = $_ -maltch 'EntryNo=(\d+)\D'
        if ($f) {
           [decimal]n = mathches[1]
           if ( n -ge $low -and n -le $high ) {
             # how to continue?
           }
         }
 }

If this is possible how can I complete the brackets?

Thanks in advance,
gooly

Loegfile Entrioes:

 PowerShell;Test.ps1;....;SeqNo=109;Tag=..
 PowerShell;Test.ps1;....;SeqNo=110;Tag=..
 PowerShell;Test.ps1;....;SeqNo=111;Tag=..
 PowerShell;Test.ps1;....;SeqNo=112;Tag=..
 PowerShell;Test.ps1;....;SeqNo=113;Tag=..
 PowerShell;Test.ps1;....;SeqNo=114;Tag=..

...

Upvotes: 0

Views: 117

Answers (1)

Joey
Joey

Reputation: 354406

Just use the pipeline how it's supposed to be used:

  1. Get the file contents

    Get-Content logfile |
    
  2. Filter for sequence number

    where {
      if ($_ -match 'SeqNo=\d+') {
        $seq = +$Matches[1]     # The + in front coerces the match to a number
        $seq -ge $low -and $seq -le $high
      } else { $false }
    }
    

For added elegance, the comparison for high and low can also be done as follows:

where { $low..$high -eq $seq }

(Might be a little slower, depending on how large the gap between $low and $high is.)

Upvotes: 2

Related Questions