question

phantom2000-5377 avatar image
0 Votes"
phantom2000-5377 asked AndreasBaumgarten answered

Compare 2 different size arrays in Powershell

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-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered

Hi @phantom2000-5377 ,

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



image.png (82.1 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered phantom2000-5377 commented

Hi @phantom2000-5377 ,

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


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.