2017-07-06 93 views
1

我正在做一系列分割來檢查文件的每一行,並輸出每行的格式化版本。輸入的Powershell獲取內容,只需要第一次出現

實施例:

02/17-07:54:32.290169 [**] [1:1:0] other [**] [Priority: 0] {TCP} 100.100.100.212:6667 -> 192.168.5.81:2848 
02/17-07:54:32.335595 [**] [1:1:0] other [**] [Priority: 0] {TCP} 100.100.100.212:6667 -> 192.168.5.81:2848 
02/17-07:54:32.335628 [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.5.81:2848 -> 100.100.100.212:6667 
06/14-06:33:47.258621 [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80 
06/14-06:33:47.258621 [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80 
06/14-06:33:47.258621 [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80 

當存在具有相同的連接ID字符串(258621,在這種情況下),我需要只是第一次出現。

這讓我的連接ID,但我不知道如何忽略任何可能跟隨相同的連接ID的行。

Get-Content $logFile -ReadCount 1 | % { 

$_.Split()[0].Split(".")[1] 

} | Out-File "C:\Log\logout.txt" 

輸出,我只想要258621中第一次出現:

290169 
335595 
335628 
258621 
258621 
258621 

更爲棘手的是,我還需要重新格式化每一行使用的東西(假設它是不是重複連接ID)像這樣的(最終,我不想在輸出連接ID):

'|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|' 

所需的輸出:

|100.100.100.212|6667|192.168.5.81|2848|other| 
|100.100.100.212|6667|192.168.5.81|2848|other| 
|192.168.5.81|2848|100.100.100.212|6667|other| 
|192.168.4.85|4662|69.192.30.179|80|other| 

謝謝!

回答

1

您可以在ForEach-Object循環中使用IF語句來確保您之前沒有處理過此連接ID。

當它被分配給一個變量$thisID,則不會傳遞到Out-File(同爲$connectionIDs

Get-Content $logFile -ReadCount 1 | % { 

    $thisID = $_.Split()[0].Split(".")[1] 

    if($thisID -notin $connectionIDs){ 
     '|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|' 
     [array]$connectionIDs += $thisID 
    } 
} | Out-File "C:\Log\logout.txt" 

輸出相匹配什麼是你的問題。

+0

美麗!謝謝! – yodish

+0

gms0ulman,你知道如何進一步過濾[9]或[11]不以「192.168」開頭的任何行嗎?我一直在玩.StartsWith,但還沒有取得任何成功。 – yodish

+0

@yodish你可以在'IF'語句中添加額外的條件。這不一定是正則表達式 - 例如'和$ line -n​​otlike <>'。推薦讀一下''''''''''不喜歡'並且給它一個去。 – gms0ulman