2

I am trying the below powerShell code to get difference. Seems it is not working. if any content change also need to display

$filePath1 = "C:\Rules1.json"
$filePath2 = "C:\Rules2.json"

$contents1 = Get-Content $filePath1 -Raw | ConvertFrom-Json
$contents2 = Get-Content $filePath2 -Raw | ConvertFrom-Json

$differences = Compare-Object $contents1 $contents2 -Property (Get-Member -InputObject $contents1 -MemberType NoteProperty).Name

foreach ($difference in $differences) {
    if ($difference.SideIndicator -eq "<=") {
      
        $difference.InputObject | Select-Object -Property $difference.PropertyName | ConvertTo-Json
    }
    elseif ($difference.SideIndicator -eq "=>") {
      
        $difference.InputObject | Select-Object -Property $difference.PropertyName | ConvertTo-Json
    }
}`

Any inputs ?. Thanks

  • 2
    Comparing objects is not as simple depending on the objects complexity / depth. Can you provide an example of your Jsons? – Santiago Squarzon May 31 '23 at 15:44
  • 2
    PowerShell's `Compare-Object` is, in a word, crap. (More charitable would be to call it "situational", I guess.) Consider using a professional diff tool, of which there are very many, including free ones. Good old-fashioned `diff` (the executable, not the PowerShell alias) is one, WinMerge for the more visually oriented is another. You can still use PowerShell to normalize both JSON files in terms of whitespace and escaping, if this is necessary. – Jeroen Mostert May 31 '23 at 15:53
  • 1
    Does this answer your question? [How to compare JSON in powershell](https://stackoverflow.com/questions/58185002/how-to-compare-json-in-powershell) – JosefZ May 31 '23 at 17:14
  • Note that `(Get-Member -InputObject $contents1 -MemberType NoteProperty).Name` will only work as intended if `$contents1` is a _single_ object. If it is an array - which requires all array elements to have the same properties - use `$contents1[0].psobject.Properties.Name` (also works if it's a single object) – mklement0 May 31 '23 at 18:51

0 Answers0