4

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" 
    }
}
2
  • here are some ideas that you can try, sort the array and loop over elements to find duplicates, use linq with using the distinct and finally, Set can't have duplicates so creating a set from array with duplicate will drop, powershell.org/2018/05/100887-2 Commented Dec 12, 2022 at 0:59
  • The details lacking in this post make it unanswerable outside of guessing. What is in $value for starters. Commented Dec 12, 2022 at 1:38

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.