Home > Back-end >  Show duplicate values within a Array
Show duplicate values within a Array

Time:12-12

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

CodePudding user response:

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

  • Related