Powershell从日志中解析日期

时间:2018-12-11 17:42:34

标签: powershell

我正在尝试解析日志文件以从日志文件条目中提取日期。我可以找到该行,但是我的解析似乎没有转换日期。

$SBError = "DbConnection"
$SBWebPath = "E:\Temp\server.log"

$result = Get-Content $SBWebPath | Select-String $SBError -casesensitive | Select -last 1 | Out-String
$result | Select-String '####<(\S+ \S+, \S+ \S+ \S+) \S+>' | ForEach-Object {
    $DBdateTime = $_.Matches[0].Groups[1].Value -as [DateTime]
    }
Write-Output $result
Write-Output $DBdateTime

server.log文件内容:

####<Dec 9, 2018 2:59:08,082 AM EST> <Info> <HTTP> Data flowing fine.
####<Dec 9, 2018 2:59:08,085 AM EST> <Warning> <HTTP> framework.db.DbConnection.

脚本输出

####<Dec 9, 2018 2:59:08,085 AM EST> <Warning> <HTTP> framework.db.DbConnection.

$ DBdateTime中的变量未填充,我怀疑是由于错误或无效的解析和/或在日志日期中包含了毫秒。

我不在乎毫秒,只在乎月日年小时分秒和AM / PM标签。另外,不必在意EST,但要记住,当服务器更改为EDT时,该值将代替EST。

感谢您的协助。

1 个答案:

答案 0 :(得分:0)

您将获得$DBDateTime的空值,因为PowerShell无法将捕获的组的值识别为有效的DateTime,因此无法将字符串强制转换为该类型。您实际上需要对其进行解析。

$culture = [Globalization.CultureInfo]::InvariantCulture
$pattern = 'MMM d, yyyy h:mm:ss,fff tt'

$DBDateTime = [DateTime]::ParseExact($_.Matches[0].Groups[1].Value, $pattern, $culture)

有关有效的格式字符串,请参见herehere

相关问题