Bagheera
Bagheera

Reputation: 1428

Powershell string parsing. Pull the date from a string of text

I have a (plain text) log file with dates that appear in most (but not all) lines of text. The date does not always appear in the same position on each line. Though not all lines have a date, there is always a date in any given set of 10 lines. A sample of the log:

03/05/2019 Event A occurred
03/05/2019 Event B occurred
Event B Details: Details Details
03/07/2019 Event C occurred
Logging completed on 03/08/2019
03/08/2019 Event D occurred

I need to get the date of last item logged. I don't need the content of the line, just the date that's in the line.

#Get the log file. Tail it because it's huge. The regex pattern matches date format dd/mm/yyyy.
$log = (Get-Content -tail 10 C:\mylog.log | Select-String -Pattern "\d{2}/\d{2}\/d{4}"
#Get the last item in the $log variable. Convert it to a string.
$string = $log[-1].toString()

#Split the string. Match each element to a date format. 
#When an element matches a date format, assign its value to a DateTime variable.
foreach ($s in $string.split() ){
    if ($s -match "\d{2}/\d{2}\/d{4}"){
        [DateTime]$date = $s
        }
    }
"The last entry in the log was made on $date"

Both parts of this code (finding the last line with a date, and pulling the date from the line) seem really kludgy. Is there a better way to do this?

Upvotes: 1

Views: 1574

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You may do the following:

[datetime]((Get-Content mylog.log -tail 10) |
  Select-String '\d{2}/\d{2}/\d{4}')[-1].Matches.Value

Select-String returns a collection MatchInfo objects. .Matches.Value of each object contains the matched string. Using the [-1] index, we can grab the last object.

Note: Select-String has a -Path parameter that can read a file. But given you don't want to read the entire file, Get-Content -Tail is used.

Upvotes: 5

Related Questions