yodish
yodish

Reputation: 807

Powershell Get-Content, want only the first occurrence

i'm doing a series of splits to examine each line of a file, and output a formatted version of each line.

Example of input:

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

When there are strings with the same connection ID (258621, in this case), I need just the first occurrence.

This gets me the connection ID, but i'm not sure how to disregard any lines that may follow with the same connection ID.

Get-Content $logFile -ReadCount 1 | % {

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

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

Output, I only want the first occurrence of 258621:

290169
335595
335628
258621
258621
258621

The trickier part is that I also need to reformat each line (assuming it isn't a duplicate connection ID) using something like this (ultimately, I don't want the connection ID in the output):

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

Desired output:

|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|

Thanks!

Upvotes: 1

Views: 1182

Answers (1)

G42
G42

Reputation: 10017

You can use an IF statement in your ForEach-Object loop to make sure you have not dealt with this connection ID before.

As it is assigned to a variable $thisID, it is not passed to Out-File (same for $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"

Output matches what's in your question.

Upvotes: 1

Related Questions