In a previous example we used HashSets to compare numeric lists, and find out which elements were found in both list, or in just one list.
The same can be done with strings. If you have two lists with names, and would like to know which names are present in both lists, or just in one, try this:
$set1 = New-Object System.Collections.Generic.HashSet[string] (,[string[]]@('Harry','Mary','Terri')) $set2 = New-Object System.Collections.Generic.HashSet[string] (,[string[]]@('Tom','Tim','Terri','Tobias')) "Original Sets:" "$set1" "$set2" # in both $copy = New-Object System.Collections.Generic.HashSet[string] $set1 $copy.IntersectWith($set2) "In Both" "$copy" # combine $copy = New-Object System.Collections.Generic.HashSet[string] $set1 $copy.UnionWith($set2) "All Combined" "$copy" # exclusive $copy = New-Object System.Collections.Generic.HashSet[string] $set1 $copy.ExceptWith($set2) "Exclusive in Set 1" "$copy" # exclusive either side $copy = New-Object System.Collections.Generic.HashSet[string] $set1 $copy.SymmetricExceptWith($set2) "Exclusive in both (no duplicates)" "$copy"
Here is the result:
Original Sets: Harry Mary Terri Tom Tim Terri Tobias In Both Terri All Combined Harry Mary Terri Tom Tim Tobias Exclusive in Set 1 Harry Mary Exclusive in both (no duplicates) Harry Mary Tobias Tom Tim