Powershell : Comparing Files

If you have a requirement to compare some files, I had 2 x text files, the first file contained the IP addresses that were in our SPF record and the second file had a list of IP addresses that we noticed in the Exchange sending report.

I needed PowerShell script to tell me which addresses appear in the first text file that doesn’t appear in the second, so I can figure of which IP addresses are not in our SPF record and need to be added:

# Path to the first text file
$file1 = "C:\IPList\sending_ip.txt"

# Path to the second text file
$file2 = "C:\IPList\authorised_spf.txt"

# Read the contents of the text files
$ips1 = Get-Content $file1
$ips2 = Get-Content $file2

# Compare the contents of the two files
$uniqueIps = Compare-Object $ips1 $ips2 | Where-Object { $_.SideIndicator -eq "<=" } | Select-Object -ExpandProperty InputObject

# Output the unique IP addresses
Write-Output ("IP addresses in " + $file1 + " that don't appear in " + $file2 + ":")
$uniqueIps

This will then give a list of IP addresses that are no in the SPF record that need to be added or steps need to be taken to avoid unauthorised sending, however if the IP address are in the CIDR location like for example x.x.x.x/24 then you will need to perform a "relaxed" search for partial matches with this:

To run this replace the "#compare the contents of the two files" of the script with this code:

# Compare the contents of the two files with partial IP matching
$uniqueIps = foreach ($ip1 in $ips1) {
    $matching = $false
    foreach ($ip2 in $ips2) {
        if ($ip2 -like "$ip1*") {
            $matching = $true
            break
        }
    }
    if (-not $matching) {
        $ip1
    }
}

Previous Post Next Post

نموذج الاتصال