Compare 2 different size arrays in Powershell

Arosh Wijepala 161 Reputation points
2021-05-19T12:54:55.01+00:00

Hi,

I have 2 arrays which can be either in equal size or can be in different in size (size determined when the code is running). I would like to compare the text in those arrays and list down the below.

  1. Output text which is present in first array but not in second array
  2. Output text not in first array but is present in second array

Appreciate it if anyone could help me with the poweshell code to achieve the above.

Thanks.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Answer accepted by question author
  1. Andreas Baumgarten 129.5K Reputation points MVP Volunteer Moderator
    2021-05-19T18:55:08.373+00:00

    Hi @Arosh Wijepala ,

    there is a typo in your script ;-)

    97956-image.png

    This is working here:

    $approvedpatches = @('patch1', 'patch2', 'patch3', 'patch4', 'patch5')  
      $installedpatches = @('patch1', 'patch2', 'patch3')  
              
      $approvedpatches | ForEach-Object {  
          if ($installedpatches -notcontains $_) {  
              Write-Host "Approved but not installed [$_]"  
          }  
      }  
      $installedpatches | ForEach-Object {  
          if ($approvedpatches -notcontains $_) {  
             Write-Host "Not approved but installed [$_]"  
          }  
     }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Andreas Baumgarten 129.5K Reputation points MVP Volunteer Moderator
    2021-05-19T15:34:09.553+00:00

    Hi @Arosh Wijepala ,

    maybe this helps:

    # Compare 2 arrays and report which string is missing  
      
    # First option  
    $array1 = @('black', 'blue', 'red', 'white', 'yellow')  
    $array2 = @('black', 'yellow', 'grey','purple','green')  
      
    $array1 | ForEach-Object {  
        if ($array2 -notcontains $_) {  
            Write-Host "`$array2 does not contain `$array1 string [$_]"  
        }  
    }  
    $array2 | ForEach-Object {  
        if ($array1 -notcontains $_) {  
            Write-Host "`$array1 does not contain `$array2 string [$_]"  
        }  
    }  
      
    # Second option  
      
    Write-Output '== means string is in both arrays  
    => missing in ReferenceObject ($array1)  
    <= missing in DifferenceObject ($array2)'  
    Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -IncludeEqual  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.