Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the "difference" between two objects in another object with the same structure using powershell?

TL;DR: This but in powershell
I’m trying to get the "difference" between a list1 and a list2 where list2 is just a sub-set of list1. (or list1 is a super-set of list2).

Keep in mind that this is not the ‘real scenario’ but the structures of both objects are the same as this:

#List of all the IDs
$list1='2','5','6','11'
$CustObject1=foreach($i in $list1){
    [pscustomobject]@{
        id=$i
    }
}
#Another list, where invalid IDs are not listed
$list2='2','5'
$CustObject2=foreach($i in $list2){
    [pscustomobject]@{
        id=$i
    }
}
#I am looking for $CustObject3 = {id = '6',id = '11'}

Now, I want to create a new "object" that contains a list of all the ‘invalid’ IDs, in our example the $CustObject3 would contain just id’s '6','11'.
The reason behind this is because I have a list of 3000 ids that are "valid" and just a couple that are "invalid" (at most 10).
I’ve tried a lot of options but I can’t get it to work, used "where", used double foreach loops, honestly I’m just frustrated at this point but I did try to make it work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this feasible?

Thanks.

>Solution :

You can use the -notin or -notcontains operators to perform the check.

#List of all the IDs
$list1='2','5','6','11'
$CustObject1=foreach($i in $list){
    [pscustomobject]@{
        id=$i
    }
}
#Another list, where invalid IDs are not listed
$list2='2','5'
$CustObject2=foreach($i in $list){
    [pscustomobject]@{
        id=$i
    }
}

$CustomObject1 | Where-Object {$_.id -notin $CustomObject2.id}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading