通过Powershell扫描一个大日志文件,通过按行删除行并在我的日期比较为真时将其停止



在这些日子里,我正在研究不同的脚本,以将行删除到不同的日志文件中。但是我仍然有一个我无法处理的文件,因为该结构比我清除的其他文件要复杂得多。为了给你一个想法,我在这里放了一些日志文件的示例行。

[ 30-10-2017 16:38:07.62 | INFO    | Some text
[ 30-10-2017 16:38:11.07 | INFO    | Some text
[1];Erreur XXXX non-gérée : Some text.
Merci de communiquer some text :
 - Some text again
 - Identifiant : XXXXXXXX-1789-XXXXX-b41b-XXXX. >> Some text
[ 02-11-2017 16:38:11.10 | INFO    | Some text
[ 02-11-2017 16:38:11.10 | INFO    | Some text
[2];88852228343 / some text
[ 03-11-2017 16:38:11.10 | INFO    | Some text
[ 03-11-2017 16:38:11.10 | INFO    | Some text
Other text here
And other one
[ 04-11-2017 16:38:11.10 | INFO    | Some text
[ 04-11-2017 16:38:11.10 | INFO    | Some text

我有一个尝试的东西,但我认为这不是做到这一点的正确方法 ->如何捕获终止错误并仍然继续我的powershell脚本

文件是4MO,现在要执行的代码不起作用,因为我以错误的方式这样做。我首先要提取日期,然后进行比较,但是当我碰到一条未在日期开始的线时,我有错误,脚本停止

try
    {
        (Get-Content $Fichier) |
            Where-Object {$_} |
            Where-Object { ([datetime]::ParseExact(([string]$_).Substring(2,19), $Format, $Culture) -ge (Get-Date).AddDays(-$Jours)) } |
            Set-Content $Fichier
        LogMessage -Message "Fichier $Fichier purgé des toutes les lignes datant de plus de $Jours jours"
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
        LogMessage -Message "$FailedItem - $ErrorMessage"
    }

我认为,如果我开始读取文件并开始删除每行,然后在找到比(今天-20天(大或相等的日期时停止删除文件的其余部分会更好。但是现在我找不到在PowerShell中找到它的正确方法。

您建议解析每行的建议方法,直到找到20天或更少的日期可能会起作用为止。我会做这样的事情:

# Placeholder for the dates we're about to parse
$DT = Get-Date
# Define the threshold once
$Limit = (Get-Date).AddDays(-$Jours)
# We'll use this flag to keep track of whether we've reached the limit or not
$Keep = $false
(Get-Content $Fichier |ForEach-Object {
    if($Keep){
        $_
    }
    elseif([datetime]::TryParseExact($_.Substring(2,19), $Format, $Culture, $null, [ref]$DT) -and $DT -ge $Limit){
        $Keep = $true
        $_
    }
}) |Set-Content $Fichier

另一个想法可能是为每天生成一个文件并为当天生成新的日志文件。

同时导出到日志窗口和文件可以使您免于日志丢失,还允许您将日志大小保持在合理的尺寸,而不会压力CPU。

i在日志上遇到了同样的问题,尤其是在使用RTF并用图标替换某些字符串以向日志上升时。并使其容易出口。

有几种生成日志的方法,但是为了我的需求,我每天都用途写一个日志,一旦一天切换一天,请清除日志窗口(00:00:00(。

最新更新