【问题标题】:Remove lines from CSV file using Powershell使用 Powershell 从 CSV 文件中删除行
【发布时间】:2023-03-30 04:55:01
【问题描述】:

我有一个包含日志信息的 CSV 文件。文件中的日期/时间信息以 UNIX 时间戳格式编写。

我想删除所有超过 5 分钟的行。我使用以下代码来执行此操作:

$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300
$Content = Import-Csv "logfile.csv" | where {$_.DateCompleted -gt $FiveMinutesAgo} 
$Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'

CSV 文件如下所示:

"DateInitiated";"DateStarted";"DateCompleted";"InitiatedBy";"Action";"Status"
"1496659208";"1496659264";"1496752840";"administrator";"Reboot server";"Completed"

无论五分钟是否已经过去,执行上述脚本行后,我的 CSV 文件最终完全为空。

【问题讨论】:

  • 我永远不会期望 powershell 能够像我想要的那样理解日期时间。我猜,您将日期时间与字符串进行比较

标签: powershell csv unix-timestamp


【解决方案1】:

我无法在测试中复制它(但可能需要实际的源文件)。我认为问题在于您还需要在 Import-CSV 上指定编码和分隔符(正如您在 Export 中已有的那样)。

试试这个:

$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300
$Content = Import-Csv "test.csv" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo} 
$Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多