Compare 2 Files for Difference

Hi All, welcome back to another Blog. I was approached by an subscriber today who is a beginer to Powershell made an awesome script which user compare-object function to compare to files. which was great start in powershell. Like i say to get to know something you need to get started. Applause to him.

The requirement was to compare 2 files to find difference, obviously there are more than one way to find difference the below script is one of those ways.

$PreFile = import-csv -LiteralPath "D:\YooAdmin\PreProcess.csv" 
$PostFile = import-csv -LiteralPath "D:\YooAdmin\PostProcess.csv"
$forHTML = @()

foreach($pline in $PostFile){
    foreach($line in $PreFile){
        if($pline -ne $line){
            $pline | export-csv -Path D:\YooAdmin\report.csv -Append -Force -NoTypeInformation
            $forHTML += $pline
            break
        }
    }
}

$forHTML | ConvertTo-Html | Out-File -FilePath D:\YooAdmin\report.html

In Summary: there are 2 file PreProcess and PostProcess both CSV
Both data in the CSV is loaded into variables and an Array to load the result for creating an html report as requested by my subscriber.

Then we get in to Loops, where you can basically check 2 file classed as array to compare.
The first loop will load the files that will be check against to see if there is any difference we call is reference and the next one is difference file.

if the a result in first loop is not equal to the result in second loop. then export that line to a CSV and add it to the Global Array, once that is done we break the loop to end it.

after completion of the loops the global varible had collected all the fields and ready to export as Export to HTML.

it’s a quick script for me but for someone who is starting with powershell this could be a milestone and moment of getting way deeper and better than me in powershell.

All the Best.

here is the result on html showing on the difference.

result from script above

Published by iamfazul

Author of the site

Leave a comment