【发布时间】:2019-09-11 17:38:20
【问题描述】:
我有这个脚本,用于处理包含日期格式为yyyy-MM-dd HH:mm:ss 的条目的日志文件。但是,我不知道如何读取格式为 yyyy-MM-dd:HH:mm:ss 作为日期格式的日志条目。
我一直在尝试使用 ParseExact() 为我转换日期,但我似乎无法让它工作,我认为这是一个错误;
无法将值“2019-09-10:12:40:03”转换为类型“System.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"
}
}
【问题讨论】:
标签: powershell date