'Compare txt files - Powershell

I have two txt files. Both contain a list of usernames:

List 1:

user1
user2
user3

List 2:

user1
user2
user7 

I want to compare these two lists. I want to know which users do not exist in both lists. So the output in this case should be a this list:

Endlist:

user3
user7

This is my code:

$list1 = get-content -Path "C:\list1.txt"
$list2 = get-content -Path "C:\list2.txt"

$endlist = foreach ($item in $list1) 
{
       if ($item -notmatch $list2)
       {
            [PSCustomObject]@{
            Name = $item 
       }

}
$endlist |Out-file "C:\endlist.txt"

What am I doing wrong?



Solution 1:[1]

Normally you would use Compare-Object for this:

$list1 = 'user1', 'user2', 'user3'
$list2 = 'user1', 'user2', 'user7'

(Compare-Object $list1 $list2).InputObject # => user3, user7

If you want to do the comparison manually, and since you want to know the objects unique to either list, you would need two loops and the use of a containment operator (-notin or -notcontains in this case):

$list1 = (Get-Content list1.txt).Trim()
$list2 = (Get-Content list2.txt).Trim()

& {
    foreach($i in $list1) {
        if($i -notin $list2) { $i }
    }
    foreach($i in $list2) {
        if($i -notin $list1) { $i }
    }
} | Out-File "endlist.txt"

Solution 2:[2]

Complementing the existing working solutions, here is another one using a HashSet, which might be faster than Compare-Object:

[Collections.Generic.HashSet[string]] $list1 = Get-Content list1.txt
[Collections.Generic.HashSet[string]] $list2 = Get-Content list2.txt

$list1.SymmetricExceptWith($list2)
$list1

Output:

user7
user3

HashSet's strangely named1SymmetricExceptWith method modifies the first set to contain only those elements that are unique to either set.

1) The mathematical term is symmetric difference.

Solution 3:[3]

Use compare-object

Compare-Object -ReferenceObject $list1 -DifferenceObject $list2 | Select-Object -ExpandProperty InputObject

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3