Remove Array Elements

by Aug 13, 2015

Did you ever need to compare two arrays? Compare-Object might help. Check this out:

$array1 = 1..100
$array2 = 2,4,80,98

Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 | 
  Select-Object -ExpandProperty InputObject

The result is the content of $array1 minus the content of $array2.

To find out the array elements that are missing in $array1 but are present in $array2, try this:

$array1 = 1..100
$array2 = 2,4,80,98, 112

Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -ExcludeDifferent -IncludeEqual | 
  Select-Object -ExpandProperty InputObject

Twitter This Tip! ReTweet this Tip!