我有一个 Powershell 脚本,我用它来解析文件中的每一行,重新格式化它,并将新字符串写入输出文件。它适用于几百行的输入文件。但是,我最终需要针对一个包含几百万行的文件运行它,而且我已经等了几个小时,但它仍然没有完成。正在关注this post ,我想我需要将 Write-Output 放在循环之外,但到目前为止我一直没有成功。
这是我当前的代码:
Foreach ($line in Get-Content $logFile) {
$arr = $line.Split()
$port1 = $arr[9].Split(":")
$port2 = $arr[11].Split(":")
$connstring = '|' + $port1[0] + "|" + $port1[1] + "|" + $port2[0] + "|" + $port2[1] + "|" + $arr[4] + "|"
Write-Output $connstring | Out-File "C:\logging\output\logout.txt" -Append
}
输入字符串的示例是:
06/14-04:40:11.371923 [**] [1:4:0] other [**] [Priority: 0] {TCP} 67.202.196.92:80 -> 192.168.1.105:55043
我需要将其重新格式化为:
|67.202.196.92|80|192.168.1.105|55043|other|
非常感谢任何帮助!
最佳答案
如果您在 Get-Content
上使用 -ReadCount
,它将具有一次一行流式传输文件的效果,而不必读取整个文件进入内存。我怀疑将写操作移出循环可能会更快。循环中更少的变量和步骤可能也会有所帮助。
假设拆分后的第四个元素不包含冒号(您没有提供文件示例),那么这样的事情应该可以解决问题:
Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|'
} | Out-File "C:\logging\output\logout.txt"
关于regex - 需要更有效的方式来写入 Powershell 中的输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44865807/