首页 > 解决方案 > 在 PowerShell 上保存带有原始标头的已清理日志文件

问题描述

有必要从带有日志的文件中删除带有数据切片的行。我的解决方案如下所示:

Get-Content C:\Users\User\Desktop\Performance_.log | 
    Select-String -Pattern '(202007|202008|202009)' | 
        %{$_.ToString()} | 
            Out-File C:\Users\User\Desktop\out.log

但是文件保存时没有标题。请告诉我如何用标题重新保存文件。我无法在 PS 上实现它。我不懂语言。非常感谢!

标签: powershell

解决方案


$header = Get-Content 'C:\Users\User\Desktop\Performance_.log' -First 1
$content = Get-Content C:\Users\User\Desktop\Performance_.log | Select-String -Pattern '(202007|202008|202009)' | % {$_.ToString()}

#Output to file
$header | Out-File C:\Users\User\Desktop\out.log
$content | Out-File C:\Users\User\Desktop\out.log -append

我两次获取内容,放入两个变量。然后我们使用 out-file 创建一个带有标题的文件,然后我们再次执行 out-file ,但这次-append设置了标志,这样标题就不会被覆盖。


如果您使用的是 CSV,我不会使用上述方法。我会改为使用 import-csv。在我看来,csv 对象比字符串更容易处理,也更灵活。

$content = import-csv 'C:\Users\User\Desktop\Performance_.log' | where-object {$_.ExampleFirstColumn -match '(202007|202008|202009)'}
$content | Export-csv "C:\Users\User\Desktop\out.log" -NoTypeInformation

只需将上面代码中的“ExampleFirstColumn”文本替换为标题的名称即可。


推荐阅读