Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show duplicate values within a Array

Can someone help me with getting the below PowerShell code?

The $value array has some duplicate values, and I'm struggling to figure out how to get the compare operator in line 2 to work.

I want it to show me if a value is repeated anywhere within the array. Thank you

foreach ($key in $value) {
    if ($key.count -gt 1) {
    Write-Host "$key" 
    }
}
like image 808
nick asdf Avatar asked Oct 18 '25 12:10

nick asdf


1 Answers

Sample data

$value = "a","a","b","b","c","d","e","f","f";

To see duplicates and the count greater than 1 use group-object and select-object to get the Name and Count properties.

$value | Group-Object | Where-Object {$_.Count -gt 1} | Select-Object Name, Count;

Output

Name Count
---- -----
a        2
b        2
f        2

One way to omit duplicates would be to use a foreach-object and then pipe that over to sort-object and use the -unique parameter to return only the unique values.

$value | ForEach-Object {$_} | Sort-Object -Unique;

Another way to omit duplicates would be to use group-object along with its -noElement parameter and then expand the Name property value without a header column.

($value | Group-Object -NoElement).Name;

Supporting Resources

  • ForEach-Object

    Standard Aliases for Foreach-Object: the '%' symbol, ForEach

  • Sort-Object

    -Unique

    Return only the unique values

  • Group-Object

    -noElement
    

    Don’t include members of each group in the output objects.

  • Select-Object

like image 141
Bitcoin Murderous Maniac Avatar answered Oct 21 '25 12:10

Bitcoin Murderous Maniac