Wendigo
Wendigo

Reputation: 73

Finding duplicates in an array in powershell

I am trying to find duplicates in a sorted array of objects with a Name property. I have the following code:

for (($i -eq 1), ($i -lt $arr.Length), ($i++))
{
    if($arr[$i] -eq $arr[$i-1])
    {
        write-host "Duplicates found: " $arr[$i].Name, $arr[$i-1].Name
    }
}

If the Name property is the same as the one in the array before it, it should in theory return the name of the duplicate. However, it's just infinitely looping and printing the name of a random object over and over. What do?

Upvotes: 0

Views: 1497

Answers (1)

Theo
Theo

Reputation: 61093

You could do this without looping using Compare-Object

To demonstrate, in $a I have your array of objects, sorted on property Name:

$a = @'
Name,SomeValue
foo,1
bar,2
baz,3
bar,4
foo,5
bar,6
'@ | ConvertFrom-Csv | Sort-Object Name

To output the duplicates you can then do

$b = $a | Select-Object Name -Unique
Compare-Object -Property Name -ReferenceObject $a -DifferenceObject $b -PassThru | Select-Object * -ExcludeProperty SideIndicator

Giving you this as result:

Name SomeValue
---- ---------
bar  4        
bar  6        
foo  5 

The same can be achieved using Group-Object and a ForEach-Object loop:

$a | Group-Object Name | Where-Object {$_.Count -gt 1} | ForEach-Object {
    $_.Group | Select-Object -Skip 1
}

Upvotes: 3

Related Questions