Search code examples
powershellobjectcompareobject

Compare-Object Find Matches and Remove Found from First Object


I'm wondering if there's a simpler way to accomplish this. I have two (JSON) objects, where they have properties that are lists of IPs (the properties are individual IPs). I'm comparing the two object properties to find any matching items and want to remove any matches from the first object ($JSONConverted). I believe I can use the remove feature (which I haven't gotten working yet). I'm really wondering if there's a simpler way to accomplish this.

$JSONConverted   = Get-Content -Raw -Path Output.json | ConvertFrom-Json
$FWJSONConverted = Get-Content -Raw -Path FWOutput.json | ConvertFrom-Json

$MatchingIPs = Compare-Object -IncludeEqual -ExcludeDifferent -ReferenceObject $FWJSONConverted.data.value -DifferenceObject $JSONConverted.data.value

$ListOfMatchingIPs = $MatchingIPs.InputObject

$JSONConverted.data.value | ForEach-Object {
    foreach ($IP in $ListOfMatchingIPs) {
        if ($_ -eq $IP) {
            $JSONConverted.remove.($_)
        }
    }
}

Here's an example of the $JSONConverted data:

{
  "number_of_elements": 1134,
  "timeout_type": "LAST",
  "name": "IP List",
  "data": [
    {
      "last_seen": 1486571563476,
      "source": "WORD: WORDS",
      "value": "10.10.10.10",
      "first_seen": 1486397213696
    },
    {
      "last_seen": 1486736205285,
      "source": "WORD: WORDS",
      "value": "10.17.24.22",
      "first_seen": 1486397813280
    },
    {
      "last_seen": 1486637743793,
      "source": "WORD: WORDS",
      "value": "10.11.10.10",
      "first_seen": 1486398713056
    }
  ],
  "creation_time": 1486394698941,
  "time_to_live": "1 years 0 mons 3 days 0 hours 0 mins 0.00 secs",
  "element_type":"IP"
}

Solution

  • Something like this should suffice (assuming you want to remove the entire child object from the data array):

    $JSONConverted.data = $JSONConverted.data | Where-Object {
        @($FWJSONConverted.data.value) -notcontains $_.value
    }