【发布时间】:2018-12-14 04:50:01
【问题描述】:
我正在整理一些自定义监控解决方案,并且日志包含不同的日期/时间条目。尝试从日志中解析日期/时间(文本值)并转换为日期值,以便我可以与其他人或系统日期进行比较。我过去使用过以下内容,但在更改为允许单个数字 DD 值和 12 小时时钟值时遇到了麻烦。
$line = "=== 2018-01-07 03:30:25,889 [ng)'] INFO"
$dateTimeString = [regex]::Matches($line, '(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)')[0].Groups[1].Value
$provider = New-Object System.Globalization.CultureInfo "en-US"
$dateTime = [datetime]::ParseExact($dateTimeString, 'yyyy-MM-dd HH:mm:ss', $provider)
但需要转换以下内容。
$line = "错误 - 2018 年 1 月 7 日 2:13:19 AM EST - 警告"
我确定 parseexact 将是: $dateTime = [datetime]::ParseExact($dateTimeString, 'MMM d, yyyy h:mm:ss tt', 提供者)
但我无法使用 Matches 函数将文本解析为这些值。
编辑: 在利用比尔的建议后,明确分配变量时,它可以工作。但是,当我将 Get-Content 假脱机到变量时,它不会。
$line = Get-Content $SBWebPath | Select-String $SBError -casesensitive |select -last 1
Write-Output $line
$line | Select-String '^####<(\S+ \S+, \S+ \S+ \S+) \S+> <Warning>' | ForEach-Object {
$dateTime = $_.Matches[0].Groups[1].Value -as [DateTime]
}
$dateTime
输出:
####<Dec 7, 2017 5:17:26 AM EST> <Warning> <HTTP>
编辑2:
如 Bill 所述,$line 被转换为数组,因此 ForEach-Object 无法解析数组。通过添加 | Out-String 到行尾,然后它就能够将其解析为字符串。
有效的最终代码:
$line = Get-Content $SBWebPath | Select-String $SBError -casesensitive | Select -last 1 | Out-String
Write-Output $line
$line | Select-String '^####<(\S+ \S+, \S+ \S+ \S+) \S+> <Warning>' | ForEach-Object {
$dateTime = $_.Matches[0].Groups[1].Value -as [DateTime]
}
$dateTime
大家干杯。
【问题讨论】:
标签: powershell datetime