最近7天阅读文字

时间:2018-12-13 15:31:10

标签: powershell

我正在尝试读取几个文本文件,这些文件的日期和成功均带有文本。 这个想法是读取最近7天内的记录,这些记录一直很成功。

日志示例:

12/5/2018 3:40:08 AM: Something_secret.txt Successfully 6335
12/6/2018 3:40:06 AM: Something_secret.txt Successfully 6337
12/7/2018 3:40:10 AM: Something_secret.txt Successfully 6338
12/8/2018 3:40:09 AM: Something_secret.txt Successfully 6342
12/9/2018 3:40:09 AM: Something_secret.txt Successfully 6342
12/10/2018 3:40:11 AM: Something_secret.txt Successfully 6342
12/11/2018 3:40:07 AM: Something_secret.txt Successfully 6342
12/12/2018 3:40:10 AM: Something_secret.txt Successfully 6344
12/13/2018 3:40:10 AM: Something_secret.txt Successfully 6347

日志类型2:

12/6/2018 3:40:06 AM: Something_secret.txt Successfully 6337
12/7/2018 3:40:10 AM: Something_secret.txt Successfully 6338
12/8/2018 3:40:09 AM: Something_secret.txt Successfully 6342
12/9/2018 3:40:09 AM: Something_secret.txt Successfully 6342
12/10/2018 3:40:11 AM: Something_secret.txt file Not found
12/11/2018 3:40:07 AM: Something_secret.txt Successfully 6342
12/12/2018 3:40:10 AM: Something_secret.txt Successfully 6344
12/13/2018 3:40:10 AM: Something_secret.txt file Not found

我创建了这个

$files = gci C:\Users\Desktop\xx
foreach ($file in $files) {
    $date = (Get-Date).AddDays(-7)-f 'MM/d/yyyy'
    $today = ((Get-Date -Format MM/d/yyyy))
    gc $file.FullName | where {
        $_ -match $date -and
        $_ -match $today -match 'Successfully'
    } | select @{n='Pathoffile';e={$file.FullName}}
}

3 个答案:

答案 0 :(得分:0)

我能做到的最简单的方法:

$last7day = [datetime]::Now.AddDays(-7)
#get content from file just provide path ( you can do it in loop)
$files = Get-Content -Path ...
#a line example
$files = '12/12/2018 3:40:08 AM: Something_secret.txt Successfully 6335'

foreach ($line in $files){

    [datetime]$date = $line  -replace "[^:]:.*",''

    if ($date -gt $last7day ) {$line}
}

答案 1 :(得分:0)

由于您的日志似乎每天只有一条记录,因此最简单的方法是从每个文件中选择最后七行,并检查它们是否都包含“成功”一词。一种方法是通过检查至少其中一行是否不包含单词,然后取反该条件。

Get-ChildItem C:\Users\Desktop\xx | Where-Object {
    -not (Get-Content $_.FullName |
        Select-Object -Last 7 |
        Where-Object {$_ -notlike '*Successfully*'})
} | Select-Object -Expand FullName

答案 2 :(得分:0)

按照安斯加的想法,最后七个条目都包含字符串successfully,但使用-Tail的{​​{1}}参数

Get-Content.

$files = gci .\*.log # C:\Users\Desktop\xx

$CkeckSuccess7 = foreach ($file in $files) {
    if (7 -eq (gc $file.FullName -Tail 7 | where {$_ -match 'Successfully'}).Count){
        $Result = $True 
    } else { 
        $Result = $False
    }
    [PSCustomObject]@{
        Pathoffile=$file.FullName
        Success7=$Result
    }
}
$CkeckSuccess7