通过逐行删除并在我的日期比较为真时停止它,使用 PowerShell 清除一个大日志文件

Purge with PowerShell a big log file by deleting line by line and stopping it when my date comparison is true

在这些天里,我正在使用不同的脚本来删除不同日志文件中的行。但是我还有一个文件无法处理,因为它的结构比我清除的其他文件要复杂一些。 为了给你一个想法,我把这个日志文件的一些示例行放在这里。

[ 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

我尝试了一些方法,但我认为这不是正确的方法 -> How to catch terminating error and still continue my PowerShell script

文件是 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

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

同时导出到日志 window 和文件可以避免日志丢失,还可以让您将日志大小保持在合理的大小而不会对 CPU 造成压力。

我在日志方面遇到了同样的问题,尤其是在使用 RTF 并将某些字符串替换为图标以增强日志时。并使其易于导出。

有几种生成日志的方法,但为了我的需要,我使用了每天写一个日志并在一天切换 (00:00:00) 后清除日志的方法 window。