Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell create a comma delimited list from array of IP's that occur $N number of times

Everywhere I have looked has shown me methods of doing this that work with physical files but, for whatever reason, not with an array. I would rather not have this data stored, then called from a file and just work directly with the array if that is possible. I am stuck using PowerShell v2 but this should still be doable. I appreciate any and all help in advance.

I have an array called $net_final that has the following values:

63.232.3.102
63.232.3.102
64.339.161.5
64.339.161.5
64.339.161.5
64.339.161.5
64.339.161.5
64.339.161.5
19.19.19.19
19.19.19.19
19.19.19.19
19.19.19.19
19.19.19.19
19.19.19.19
19.19.19.19
63.339.161.7
63.339.161.7
63.339.161.7
63.339.161.7
63.339.161.7

I then do the following to get a list of IP's that occur 5 or more times in this array:

($net_final | Group-Object | Where-Object {$_.Count -ge 5} | Format-Table -HideTableHeaders -Property Name | Out-String).Trim()

Which gets me this output:

64.339.161.5
19.19.19.19
63.339.161.7

However I cannot seem to get them comma delimited on the same line. Making a comma delimited list out of just the array is fairly uncomplicated with things like $net_final -Join "," and ($net_final | Select-Object -Unique) -Join ",", but I need to grab array items that occur $N number of times.

Expected output:

64.339.161.5,19.19.19.19,63.339.161.7

like image 871
beardedeagle Avatar asked May 01 '14 22:05

beardedeagle


3 Answers

Here you go, a nice little one-liner for you:

($net_final|group|?{$_.count -ge 5}|Select -ExpandProperty Name) -join ","

That will output:

64.339.161.5,19.19.19.19,63.339.161.7
like image 61
TheMadTechnician Avatar answered Nov 02 '22 14:11

TheMadTechnician


I had trouble with the solution given by TheMadTechnician, but found the following works great:

$my_array -join ","

like image 22
mgood1 Avatar answered Nov 02 '22 16:11

mgood1


Even faster / simpler to read:

$test = (1,3,7,7,3,2,1)
$($test | sort -Unique) -join "," 

1,2,3,7

You can pipe any array into sort with the -unique flag to dedupe; the wrapped variable can then be joined with your preferred delimiter.

like image 5
user3166350 Avatar answered Nov 02 '22 16:11

user3166350