powershellreplacetimestampedit

Powershell Parse logfile and add timestamps when missing


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
  }
 }

Solution

  • 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