将已清理的日志文件与原始标头一起保存在PowerShell上



有必要从带有日志的文件中删除带有数据切片的行。我的解决方案是这样的:

Get-Content C:UsersUserDesktopPerformance_.log | 
Select-String -Pattern '(202007|202008|202009)' | 
%{$_.ToString()} | 
Out-File C:UsersUserDesktopout.log

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

$header = Get-Content 'C:UsersUserDesktopPerformance_.log' -First 1
$content = Get-Content C:UsersUserDesktopPerformance_.log | Select-String -Pattern '(202007|202008|202009)' | % {$_.ToString()}
#Output to file
$header | Out-File C:UsersUserDesktopout.log
$content | Out-File C:UsersUserDesktopout.log -append

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


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

$content = import-csv 'C:UsersUserDesktopPerformance_.log' | where-object {$_.ExampleFirstColumn -match '(202007|202008|202009)'}
$content | Export-csv "C:UsersUserDesktopout.log" -NoTypeInformation

只需将";ExampleFirstColumn";上面代码中的文本以及标题的名称。

相关内容

最新更新