Compare two arrays and only get objects that are not part of the other one

Hi,

I currently have two arrays

array1
array2

I want to have all objects of array1 that are not part of array2

Im using this::
$array3 = $array1 | Where {$array2.ObjectID -NotContains $_.ObjectID}

This is almost working except for one issue:
This also adds objects of array2 that are not an object of array1 to array3, but this is NOT what i want. I want only to add objects of array 1 if they are not an object within array2

What am I doing wrong here?

BG
Gunnar

gugoeb,
Welcome to the forum. :wave:t4:

In PowerShell we work with objects and properties. To compare objects we use

For your requirement it would be something like this:

$Array1 = @'
ObjectID
1
2
3
4
5
'@ | 
ConvertFrom-Csv

$Array2 = @'
ObjectID
1
3
5
6
7
'@ | 
ConvertFrom-Csv

Compare-Object -ReferenceObject $Array1 -DifferenceObject $Array2 -Property ObjectID -PassThru | 
    Where-Object -Property SideIndicator -EQ -Value '<='

And BTW: When you post code please format it as code using the preformatted text button ( </> ). Simply place your curseor on an empty line, click the button and paste your code.

Thanks in advance

The example you show would not do what you state. No members of $array2 will end up in $array3. Assuming the object has property ObjectID, it should do exactly what you desire.

$array1 = 1..4 | ForEach-Object {
    [PSCustomObject]@{
        ObjectID = $_
    }
}

$array2 = 3..6 | ForEach-Object {
    [PSCustomObject]@{
        ObjectID = $_
    }
}

$array3 = $array1 | Where {$array2.ObjectID -NotContains $_.ObjectID}

$array3

ObjectID
--------
       1
       2