Zack
Zack

Reputation: 9

Comparing two text files and output the differences in Powershell

So I'm new to the Powershell scripting world and I'm trying to compare a list of IPs in text file against a database of IP list. If an IP from (file) does not exist in the (database) file put it in a new file, let's call it compared.txt. When I tried to run the script, I didn't get any result. What am I missing here?

$file = Get-Content "C:\Users\zack\Desktop\file.txt"
$database = Get-Content "C:\Users\zack\Desktop\database.txt"

foreach($line1 in $file){
$check = 0
foreach($line2 in $database)
{
    if($line1 != $line2)
    {
        $check = 1
    }
    else
    {
        $check = 0
        break
    }
}
 if ($check == 1 ) 
 {
    $line2 | Out-File "C:\Users\zack\Desktop\compared.txt"
 }
}

Upvotes: 1

Views: 97

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 61323

There is a problem with your use of PowerShell comparison operators unlike in C#, equality and inequality are -eq and -ne, and since PowerShell is a case insensitive language, there is also -ceq and -cne.

There is also a problem with your code's logic, a simple working version of it would be:

$database = Get-Content "C:\Users\zack\Desktop\database.txt"

# iterate each line in `file.txt`
$result = foreach($line1 in Get-Content "C:\Users\zack\Desktop\file.txt") {
    # iterate each line in `database.txt`
    # this happens on each iteration of the outer loop
    $check = foreach($line2 in $database) {
        # if this line of `file.txt` is the same as this line of `database.txt`
        if($line1 -eq $line2) {
            # we don't need to keep checking, output this boolean
            $true
            # and break the inner loop
            break
        }
    }

    # if above condition was NOT true
    if(-not $check) {
        # output this line, can be `$line1` or `$line2` (same thing here)
        $line1
    }
}
$result | Set-Content path\to\comparisonresult.txt

However, there are even more simplified ways you could achieve the same results:

$database = Get-Content "C:\Users\zack\Desktop\database.txt"
$result   = foreach($line1 in Get-Content "C:\Users\zack\Desktop\file.txt") {
    if($line1 -notin $database) {
        $line1
    }
}
$result | Set-Content path\to\comparisonresult.txt
$database = Get-Content "C:\Users\zack\Desktop\database.txt"
Get-Content "C:\Users\zack\Desktop\file.txt" | Where-Object { $_ -notin $database } |
    Set-Content path\to\comparisonresult.txt
$file = [System.Collections.Generic.HashSet[string]]@(
    Get-Content "C:\Users\zack\Desktop\file.txt"
)
$database = [string[]]@(Get-Content "C:\Users\zack\Desktop\database.txt")
$file.ExceptWith($database)
$file | Set-Content path\to\comparisonresult.txt

Upvotes: 2

Related Questions