2017-07-01 179 views
2

我有一個Powershell腳本用於解析文件中的每一行,重新格式化它,並將新字符串寫入輸出文件。它適用於具有幾百行輸入文件。但是,我需要最終對一個擁有幾百萬行的文件運行它,而且我一直在等待幾個小時,但它還沒有完成。在this post之後,我想我需要在循環之外加入Write-Output,但是到目前爲止我還沒有成功。在Powershell中寫入輸出文件的更有效方法

這是我當前的代碼:

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| 

任何幫助非常感謝!

+0

你只需要上尉那麼IP /端口和內容?正則表達式可能能夠更快地完成你想要的。 – TheIncorrigible1

+0

是的,正確的。 IP,端口和標籤(在這種情況下是「其他」)。 – yodish

回答

3

如果您在Get-Content上使用-ReadCount,它將會使文件一次一行地流式傳輸,而不必將整個文件讀入內存。我懷疑在循環之外移動寫入操作可能會更快。循環內的變量和步驟較少可能也有幫助。

假設那麼這樣的事情是應該做的伎倆第四個元素之後的拆分不包含冒號(您沒有提供與實例文件的):

Get-Content $logFile -ReadCount 1 | % { 
    '|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|' 
} | Out-File "C:\logging\output\logout.txt" 
+0

謝謝戴夫;到目前爲止,我對代碼的初步測試看起來速度稍快,但不幸的是沒有太多。我用一個輸入字符串和重新格式化的字符串的例子更新了我的原始帖子。也許我的代碼邏輯需要調整? – yodish

+0

更新,此代碼大大加快。謝謝戴夫! – yodish

1

威力幫助消除你的字串建設

$connstring = "|$($port1[0])|$($port1[1])|$($port2[0])|$($port2[1])|$($arr[4])|" 

嘗試使用Measure-Command與樣本數據集來測試加法。

1

嘗試這樣的事情:

$test="06/14-04:40:11.371923 [**] [1:4:0] other [**] [Priority: 0] {TCP} 67.202.196.92:80 -> 192.168.1.105:55043" 

[email protected]" 
{Row:06/14-04:40:11.371923 [**] [1:4:0] {Text:other} [**] [Priority: 0] \{TCP\} {IPIN:67.202.196.92}:{PORTIN:80} -> {IPOUT:192.168.1.105}:{PORTOUT:55043}} 
"@ 

$test| ConvertFrom-String -TemplateContent $template |%{"|{0}|{1}|{2}|{3}|{4}|" -f $_.Row.IPIN, $_.Row.PORTIN, $_.Row.IPOUT , $_.Row.PORTOUT , $_.Row.Text } 

,但你可以direectly導出爲CSV格式是這樣的:

[email protected]" 
{Row:06/14-04:40:11.371923 [**] [1:4:0] {Text:other} [**] [Priority: 0] \{TCP\} {IPIN:67.202.196.92}:{PORTIN:80} -> {IPOUT:192.168.1.105}:{PORTOUT:55043}} 
"@ 

Get-Content $logFile | ConvertFrom-String -TemplateContent $template | % { 
[pscustomobject]@{ 
IPIN=$_.Row.IPIN 
PORTIN=$_.Row.PORTIN 
IPOUT=$_.Row.IPOUT 
PORTOUT=$_.Row.PORTOUT 
Text=$_.Row.Text 
} 

} | export-csv "C:\logging\output\logout.csv" -Append -NoType 
+1

在第二個代碼中,最後一行是另一個foreach,應將IMO註釋掉或刪除。否則,+1我認爲'ConvertFrom-String'與模板嚴重低估 – LotPings