Home > Mobile >  Compare txt files - Powershell
Compare txt files - Powershell

Time:04-27

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?

CodePudding user response:

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"

CodePudding user response:

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 named1 SymmetricExceptWith method modifies the first set to contain only those elements that are unique to either set.

1) The mathematical term is symmetric difference.

CodePudding user response:

Use compare-object

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