1

I have this script which I have working for log files containing entries with a date format of yyyy-MM-dd HH:mm:ss. However, I'm at a loss how to read log entries formatted with yyyy-MM-dd:HH:mm:ss as the date format.

I've been trying use ParseExact() to convert the date for me but I just can't seem to get it to work, I get this as an error;

Cannot convert value "2019-09-10:12:40:03 " to type "System.DateTime". Error: "String was not recognized as a valid DateTime."

$logfile =  "C:\logs\APP.log"
cat $logfile | Select-String "ERROR" -SimpleMatch | select -Expand line | foreach {
    $_ -match '(.+)ERROR(.+)'| Out-Null 

    $error_time = [DateTime]($matches[1])

    $culture = [Globalization.CultureInfo]::InvariantCulture
    $error_time = [DateTime]::ParseExact("$matches[1]", "yyyy-MM-dd:HH:mm:ss", $culture)
    if ($error_time -gt (Get-Date).AddMinutes(-60)) {
        Write-Host "CRITICAL: There is an error in the log file" $logfile "around "$error_time;
    } else {
        Write-Host "OK: There was no errors in the past 24h"
    }
}

1 Answer 1

3

There are two issues with your code:

  1. [DateTime]($matches[1]):
    Your timestamp has a colon between the date and time portions. That is not among the formats that PowerShell could cast to a DateTime object.

  2. If you take a closer look at the error message you'll notice that there's trailing whitespace after the timestamp. The pattern you're using in ParseExact() doesn't account for that. Also, putting $matches[1] in double quotes ("$matches[1]") does not get you the value of the first capturing group as a string. What you're effectively getting is "$matches" + "[1]" because PowerShell does not support index- or dot-access with variables in strings.

Remove the double quotes and trim the value of the capturing group to remove the trailing whitespace.

$culture = [Globalization.CultureInfo]::InvariantCulture
$error_time = [DateTime]::ParseExact($matches[1].Trim(), 'yyyy-MM-dd:HH:mm:ss', $culture)

Also, remove the line

$error_time = [DateTime]($matches[1])
Sign up to request clarification or add additional context in comments.

1 Comment

This has worked perfectly, thank you for your help with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.