2

I have a hashtable created from an array like this:

$employeesHashtable = $employees | Group-Object -Property Initials -AsHashTable

How do I find keys having multiple values?

2 Answers 2

2

The alternative to using .GetEnumerator() can be using the hash table Keys, the key collection implements ICollection and can be enumerated without issues:

$keysWithMultipleValues = $employeesHashtable.Keys.where{ $employeesHashtable[$_].Count -gt 1 }
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up with this:

$keysWithMultipleValues = $employeesHashtable.GetEnumerator() | `
  ForEach-Object { [PSCustomObject]@{ Key = $_.Key; Count = $_.Value.Count } } | `
  Where-Object { $_.Count -gt 1 }

2 Comments

FWIW you can skip the ForEach-Object invocation completely: $employeesHashtable.GetEnumerator() |Where-Object { $_.Value.Count -gt 1 } (will likely be slightly faster)
If you're using .GetEnumerator() you should reverse the order for efficiency, first filter: $employeesHashtable.GetEnumerator() | Where-Object { $_.Value.Count -gt 1 } then construct your object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.