Author Posts

October 20, 2015 at 6:54 am

I want to compare 2 xml files. Is there any way that I can get line numbers along with the difference result?

$book1=Get-Content "D:\Site1\web.config"
$book1=$book1 | Foreach {$_.Trim()}
$book2=Get-Content "D:\Site2\web.config"
$book2=$book2 | Foreach {$_.Trim()}
Compare-Object $book1 $book2 | Format-Table InputObject, SideIndicator, @{Label="Line Number";Expression={$_.InputObject.ReadCount}}

October 20, 2015 at 8:18 am

Hey Shelly. What you are asking for could get a bit complicated. If you want to do spot checks of something like this, I would use Beyond Compare, it's free and gives you a GUI to do what you want. If you are trying to make sure all of the servers have the same configuration, you should look at Desired State Configuration versus something manual.

However, to give a basic example, Get-Content places everything in an array. So, you would use the index of the array to compare the values on the same line on the file. Indexes start at zero versus 1, so we subtract from the count and to get the line number we would add the 1 back:

Test.txt

Red
Blue
White
Yellow

Test2.txt

Red
Blue
Brown
Yellow

Script:

$file1 = Get-Content C:\Temp\test.txt
$file2 = Get-Content C:\Temp\test2.txt

for ($i = 0; $i -le ($file1.Count - 1); $i++) {
    if ($file1[$i] -ne $file2[$i]) {
        "Line {0} doesn't match" -f ($i + 1)
    }
}

Output:

Line 3 doesn't match

October 20, 2015 at 11:01 pm

It did not work for xml files. However this worked-
$abc = gc .\z.txt | %{$i = 1} { new-object psobject -prop @{LineNum=$i;Text=$_}; $i++}
$cde = gc .\x.txt | %{$i = 1} { new-object psobject -prop @{LineNum=$i;Text=$_}; $i++}
Compare-Object $abc $cde -Property Text -PassThru -IncludeEqual