Powershell Parse logfile and add timestamps when missing

60 views Asked by At

Given a log file like this:

10:36:36:891 blah blah 1
10:36:36:891 blah blah 2
  blah blah 3
10:37:00:231 blah blah 4

I would like to parse the log file, looking at each line to determine if there is a timestamp. If not, add (prepend) the previous timestamp to the line and keep going to the next line, then ultimately save the log file with the changes.

I'm new to PowerShell but probably need to start with something like:

foreach($line in Get-Content .\file.txt)
 if($line -match $regex){
   # Work here
  }
 }
2

There are 2 answers

0
Santiago Squarzon On BEST ANSWER

I would use a switch with the -Regex and -File flags. As an example, using the data provided in question:

@'
10:36:36:891 blah blah 1
10:36:36:891 blah blah 2
  blah blah 3
10:37:00:231 blah blah 4
'@ | Set-Content .\test.log

$parsedLog = switch -File .\test.log -Regex {
    '^(?:[0-9]{2}:){3}[0-9]{3}' { $_ } # if the line starts with a timestamp, output it as is
    Default { '{0} {1}' -f $Matches[0], $_.TrimStart() } # else, prepend the previous timestamp
}
$parsedLog | Set-Content .\test.log
3
lit On

This assumes a specific format for the timestamp at the beginning of the line.

foreach ($line in (Get-Content .\file.txt)) {
    if ($line -match '^(\d{2}:\d{2}:\d{2}:\d{3}).*') {
        Write-Host "The timestamp is $($Matches[1])"
    }
}

Do you need to convert the timestamp into a [datetime] object?