Find Duplicates in an Array

Read Time:52 Second

Need to find duplicates in an array? It’s as simple as using a group object. So we take an array, and group the array by property or group of properties. Then we search those groups for any group that has a count of 2 or greater. Then we display those groups. Here is the heart of the code:

 $InputObject | Group-Object -Property $Property | Where-Object { $_.count -ge 2 } | ForEach-Object { $_.group }

Now it’s as simple as wrapping this one-liner into a function. The Group-object property switch can take multiple inputs. So it’s best to set that as a list of strings. Here we go:

The Script

function Get-SHDArrayDuplicates {
    [cmdletbinding()]
    param (
        [array]$InputObject,
        [string[]]$Property
    )
    $InputObject | Group-Object -Property $Property | Where-Object { $_.count -ge 2 } | ForEach-Object { $_.group }
}

You Might Also Like

Leave a Reply

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.