【发布时间】:2019-09-07 05:29:42
【问题描述】:
我正在尝试编写代码来解析特定日期范围内的日志文件,日志文件内容如下:
例如:提取日期(11/28 07:08:46)并解析。
[C79C] ComputerName:BETHGARWICK UserID:A0006 Beth Garwick Station 9 LanId: | (11/28 07:08:46) | Client is disconnected from agent.
[C79C] ComputerName:BETHGARWICK UserID: Logged out Station 0 LanId: | (11/28 07:08:51) | Client is connected to agent.
[EB7C] ComputerName:APT UserID:A0005 Kelley Zajac Station 4 LanId: | (11/28 07:12:08) | Client is disconnected from agent.
[EB7C] ComputerName:APT UserID:A0005 Kelley Zajac Station 4 LanId: | (11/28 07:12:13) | Client is connected to agent.
[EC44] ComputerName:KCUTSHALL-PC UserID:GO kcutshall Station 9900 LanId: | (11/28 07:55:08 - 11/28 07:55:18) | Average limit (300) exceeded while pinging www.google.com [74.125.224.82] 3 times
[EC44] ComputerName:KCUTSHALL-PC UserID:GO kcutshall Station 9900 LanId: | (11/28 07:55:23) | Average limit (300) exceeded while pinging www.google.com [www.google.com]
[EC44] ComputerName:KCUTSHALL-PC UserID:GO kcutshall Station 9900 LanId: | (11/28 07:55:29 - 11/28 07:55:49) | Average limit (300) exceeded while pinging www.google.com [74.125.224.50] 5x
[EC44] ComputerName:KCUTSHALL-PC UserID:GO kcutshall Station 9900 LanId: | (11/28 07:55:54 - 11/28 07:56:45) | Average limit (300) exceeded while pinging www.google.com [74.125.224.50] 11 times
[EC44] ComputerName:KCUTSHALL-PC UserID:GO kcutshall Station 9900 LanId: | (11/28 07:56:50) | Average limit (300) exceeded while pinging www.google.com [www.google.com]
试过 .net 函数 parseexact(), parse() 但没有用。
$patter = 'mm/dd'
$culture = [Globalization.CultureInfo]::InvariantCulture
$logfiles = Get-Content -Path "C:\Users\ABC\Desktop\Temp\HTTPS\QoS_logs\test.logs"
$logfiles | foreach {
$dateasText = $_.ToString().Split("|")[1].Replace("(","").Replace(")","").Trim()
$date = [DateTime]::ParseExact($dateasText,$pattern,$null)
使用“3”个参数调用“ParseExact”的异常:“字符串未被识别为有效的 DateTime。” 在“C:\Users\ABC\Desktop\Temp\HTTPS\QoS_logs\test.logs:23 char:1 + $date = [DateTime]::ParseExact($dateasText,$pattern,$null) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : 格式异常
【问题讨论】:
-
你还没告诉我们
$pattern的内容是什么,我们怎么可能帮忙? -
@PanagiotisKanavos 我刚刚在 C# 中尝试过,
DateTime.ParseExact("09/06", "MM/dd", null)结果在 2019 年 9 月 6 日 -
未经测试:你是不是在这里错过了一个 n:
$patter = 'mm/dd'? -
@ThomasSchremser 哎呀,我在尝试该模式时有一个错字:
"MM//dd"。 -
你的第一行代码应该是
$pattern = 'MM/dd',模式的n缺失,月份是大写MM,小写mm是分钟。除此之外,您的行提取文本在空行上失败。使用更好的正则表达式来 grep 日期。
标签: powershell