Compare 2 files and get line number

Welcome Forums General PowerShell Q&A Compare 2 files and get line number

Viewing 2 reply threads
  • Author
    Posts
    • #31048
      Participant
      Topics: 3
      Replies: 7
      Points: 0
      Rank: Member

      I want to compare 2 xml files. Is there any way that I can get line numbers along with the difference result?
      <br />$book1=Get-Content "D:\Site1\web.config"<br />$book1=$book1 | Foreach {$_.Trim()}<br />$book2=Get-Content "D:\Site2\web.config"<br />$book2=$book2 | Foreach {$_.Trim()}<br />Compare-Object $book1 $book2 | Format-Table InputObject, SideIndicator, @{Label="Line Number";Expression={$_.InputObject.ReadCount}}<br />

    • #31057
      Participant
      Topics: 16
      Replies: 1792
      Points: 3,290
      Helping Hand
      Rank: Community Hero

      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

      Test2.txt

      Script:

      Output:

    • #31075
      Participant
      Topics: 3
      Replies: 7
      Points: 0
      Rank: Member

      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

Viewing 2 reply threads
  • The topic ‘Compare 2 files and get line number’ is closed to new replies.