首页 > 解决方案 > 获取特定日期的日志文件

问题描述

我想在我的计算机“C:\logFiles”中保存由另一台 PC 中的程序生成的日志文件的特定日期,我将从它获取日志文件的路径是“C:\Sut\Stat\03-2021.log”

示例:此文件“C:\Sut\Stat\03-2021.Sutwin.log”包含火星月的所有日志,但我只想获取从 19-03-2021 到 26-03-的最后 7 天的日志- 2021

我在互联网上找到了这个脚本,但我不适合我,我需要一些帮助:

附件照片中的 .log 文件示例:

第一个屏幕截图的其余图像:

  1. 我的电脑名称:c01234

  2. PC 内容日志文件的名称:c06789

  3. 我将从中获得信息的文件:03-2021.Sutwin.log(存在于 pc c06789 中)

  4. 我想将最近 7 天的内容传输到我的 PC c01234 中名为 Week11_LogFile 的文件夹中

$log = "2015-05-09T06:39:34 Some information here

2015-05-09T06:40:34 Some information here
" -split "`n" | Where {$_.trim()}

#using max and min value for the example so all correct dates will comply
$upperLimit = [datetime]::MaxValue #replace with your own date
$lowerLimit = [datetime]::MinValue #replace with your own date

$log | foreach {
$dateAsText = ($_ -split '\s',2)[0]
try
{
$date = [datetime]::Parse($dateAsText)
if (($lowerLimit -lt $date) -and ($date -lt $upperLimit))
{
$_ #output the current item because it belongs to the requested time frame
}
}
catch [InvalidOperationException]
{
#date is malformed (maybe the line is empty or there is a typo), skip it
}
}

标签: powershellshell

解决方案


根据您的图像,您的日志文件看起来像简单的制表符分隔文件。

假设是这种情况,这应该有效:

# Import the data as a tab-delimited file and add a DateTime column with a parsed value
$LogData = Import-Csv $Log -Delimiter "`t" |
    Select-Object -Property *, @{n='DateTime';e={[datetime]::ParseExact($_.Date + $_.Time, 'dd. MMM yyHH:mm:ss', $null)}}

# Filter the data, drop the DateTime column, and write the output to a new tab-delimited file
$LogData | Where-Object { ($lowerLimit -lt $_.DateTime) -and ($_.DateTime -lt $upperLimit) } |
    Select-Object -ExcludeProperty DateTime |
    Export-Csv $OutputFile -Delimiter "`t"

这里的主要缺点是在 Windows Powershell(v5.1 及更低版本)上,您只能导出引用的数据。在 Powershell 7 及更高版本上,如果这很重要,您可以使用它-UseQuotes Never来防止字段被双引号识别。

唯一的另一个缺点是,如果这些日志文件很大,那么导入和处理它们将需要很长时间。您可以通过使上述单线像这样来提高性能:

Import-Csv $Log -Delimiter "`t" |
    Select-Object -Property *, @{n='DateTime';e={[datetime]::ParseExact($_.Date + $_.Time, 'dd. MMM yyHH:mm:ss', $null)}} |
    Where-Object { ($lowerLimit -lt $_.DateTime) -and ($_.DateTime -lt $upperLimit) } |
    Select-Object -ExcludeProperty DateTime |
    Export-Csv $OutputFile -Delimiter "`t"

但是如果日志文件非常大,那么您可能会遇到不可避免的性能问题。


推荐阅读