Search code examples
powershellcomparetxt

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

  • 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"