Compare array to add or remove item

Welcome Forums General PowerShell Q&A Compare array to add or remove item

Viewing 4 reply threads
  • Author
    Posts
    • #245760
      Participant
      Topics: 11
      Replies: 15
      Points: 104
      Rank: Participant

      I have two array which I like to compare to remove or add name to file

      for example

      $oldArray= @”a”, “b”, “c”

      [email protected]”a”, “b”, “d”, “e”

      I would like to compare both array and add d & e but remove c because c doesnt existed in new array

      $oldArray= @(“a”, “b”, “c”)
      [email protected](“a”, “b”, “d”, “e”)

      foreach ($a in $oldArray) {
      if ($newarray -contains $a)
      { “Doesnt existed in new array so lets add it” }
      }

       

    • #245766
      Participant
      Topics: 11
      Replies: 15
      Points: 104
      Rank: Participant

      I got this which is working but is it better way to do it

       

      $oldArray= @(“a”, “b”, “c”)
      [email protected](“a”, “b”, “d”, “e”)

      Compare-Object -IncludeEqual -ReferenceObject $oldArray -DifferenceObject $newarray | Where-Object -FilterScript {

      if($_.SideIndicator -eq “=>”){Write-Host “New Object – ” $_.InputObject}
      if($_.SideIndicator -eq “<=”){Write-Host “Remove Object – ” $_.InputObject}

      }

    • #245769
      Participant
      Topics: 15
      Replies: 1776
      Points: 3,218
      Helping Hand
      Rank: Community Hero

      Compare being the key word, look at Compare-Object:

      Output:

      • This reply was modified 1 month, 4 weeks ago by Rob Simmers.
    • #245778
      Participant
      Topics: 11
      Replies: 15
      Points: 104
      Rank: Participant

      Thank you

    • #245844
      Participant
      Topics: 8
      Replies: 568
      Points: 2,171
      Helping Hand
      Rank: Community Hero

      And another option.

      Output

Viewing 4 reply threads
  • You must be logged in to reply to this topic.