将系统日期与日志日期进行比较,并且仅在系统日期之后显示日志条目-pshell

时间:2018-11-20 17:08:00

标签: powershell date split

我有日期格式为yyyy-MM-dd HH:mm:ss,FFF的日志文件,例如:

2018-11-20 15:45:58,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-20 15:45:58,021 [No|SeSt] [2] [Session#-2,Username=2] INFO  is running
2018-11-20 15:45:58,031 [No|SeSt] [3] [Session#-3,Username=3] INFO  is running

我需要将其与系统日期进行比较,并仅显示大于设置的系统日期的日志

我已经有一个$logDate格式的yyyy-MM-dd HH:mm:ss,FFF,但是$_.[datetime]实际上是一个系统日期,带有今天的日期和00:00:00,000

get-content -Path $file -Tail 100 |  where-object {  $_.[datetime] $_.split()[0] -le $logDate}

我可能需要从日志文件1st中提取日期?

谢谢

2 个答案:

答案 0 :(得分:1)

这确实符合您的描述。但是,我想不出为什么要测试未来 ... [咧嘴]

中的日期
# read in a text file
#    in real life, use Get-Content
$InStuff = @'
2018-11-21 21:21:21,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-19 19:19:19,021 [No|SeSt] [2] [Session#-2,Username=2] INFO  is running
2018-11-20 20:20:20,031 [No|SeSt] [3] [Session#-3,Username=3] INFO  is running
2018-11-22 22:22:22,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-23 23:23:23,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-18 18:18:18,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
'@ -split [environment]::NewLine

# get today at midnite, not "now"
$Today = (Get-Date).Date

$Results = foreach ($IS_Item in $InStuff)
    {
    $DateString = $IS_Item.Split(' ')[0].Trim()
    $ParsedDate = [datetime]::ParseExact($DateString, 'yyyy-MM-dd', $Null)

    if ($ParsedDate -gt $Today)
        {
        $IS_Item
        }
    }

$Results

输出...

2018-11-21 21:21:21,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-22 22:22:22,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running
2018-11-23 23:23:23,011 [No|SeSt] [1] [Session#-1,Username=1] INFO  is running

答案 1 :(得分:1)

您的命令没有@Lee_Dailey的回答那么糟糕,而且效率更高,
只需删除$_.前面的[datetime](并且-le应该为-gt),
但仅使用日期进行比较。

假设您要比较所有日期元素,包括几分之一秒:

## Q:\Test\2018\11\20\SO_53398055.ps1
$File = '.\SO_53398055.log'
$dtFormat = 'yyyy-MM-dd HH:mm:ss,FFF'
$logDate = [datetime]::ParseExact('2018-11-20 15:45:58,018',$dtFormat,$Null)

Get-Content -Path $file -Tail 100 |
  Where-Object {[datetime]::ParseExact( ($_.split('[')[0]).Trim(), $dtFormat,$Null) -gt $logDate}

“位置”看起来有点拥挤,因为我使用[拆分了输入行,然后需要修剪尾随空格。
我选择的logDate在第一个和第二个日志条目之间,并且正如您的文本所说的only logs which are greater than a set system date偏离了您的代码,后者的比较甚至更少,甚至我期望此输出

> Q:\Test\2018\11\20\SO_53398055.ps1
2018-11-20 15:45:58,021 [No|SeSt] [2] [Session#-2,Username=2] INFO  is running
2018-11-20 15:45:58,031 [No|SeSt] [3] [Session#-3,Username=3] INFO  is running