0

I had this code for a function that I can call to compare contents of two files and make it output the difference. The idea is that I am comparing two versions of the same file which is the yesterday and the today version of the file and I am catching if there has been any changes in the today's version compared to the yesterday's.

function Compare-Files {
[cmdletbinding()]
param(
    [parameter(mandatory)]
    [ValidateScript({Test-Path $_ -PathType Leaf})]
    [System.IO.FileInfo]$BeforeFile,
    [parameter(mandatory)]
    [ValidateScript({Test-Path $_ -PathType Leaf})]
    [System.IO.FileInfo]$AfterFile
)

    $file1 = Get-Content $BeforeFile
    $file2 = Get-Content $AfterFile

    $totalCount = ($file1.Count, $file2.Count | Measure-Object -Maximum).Maximum
  
    for($i=0;$i -lt $totalCount;$i++)
    {
        $status = 'NO CHANGE'

        if($file1[$i] -ne $file2[$i])
        {
            $status = 'UPDATED'
        }

        [pscustomobject]@{
            Before = $file1[$i]
            After = $file2[$i]
            Status = $status
        }
    }
}

This code works perfectly however I need a little bit of modification and did my research but keeps finding myself stuck in a rut. This compare code compares the contents of the two files line per line, so if a new line has been added in the today version then it totally throws off the compare process since from that point on those lines are no longer matching. I guess what I'm trying to do here is to get the contents of the yesterday file and validate if they still exist on the today file and report if anything has been added, deleted, or updated and I think that processing this line per line isn't gonna give me the ideal result. I would greatly appreciate if anyone could give me a hand on this. Thank you so much in advanced.

  • You should consider using [Compare-Object](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/compare-object?view=powershell-7.1#example-1---compare-the-content-of-two-text-files) – Abdul Niyas P M Nov 05 '21 at 06:17
  • Please reveal some details about the contents of the files as other compare methods then "*compares the contents of the two files line per line*" are only possible if the files aren't just text. Please also have a look at: [In Powershell, what's the best way to join two tables into one?](https://stackoverflow.com/a/45483110/1701026) – iRon Nov 05 '21 at 07:37
  • I suggest you split the task into how to detect "added", "deleted" and "updated" lines instead of trying to do it all at once. Think about how _you_ would do it, when you go through each file line by line. Hint: you have to use two line counters, one for each file to be able to resynchronize after differences. – zett42 Nov 05 '21 at 11:35

0 Answers0