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