user3509273
user3509273

Reputation: 31

If a user exists in both objects, return their value from object 1 [Powershell]

I'm trying to compare two different objects and return the ID of the user from Object 1 if their email address exists in object 2.

I.e. Object 1

|   user    |    id      |   emailaddress    |
+-----------+------------+--------------------+
| test user | asfasfasdf | [email protected] |
| ima test  | bsvxcffasd | [email protected]  |
+-----------+------------+--------------------+

    Object 2
+--------------------+
|   email   |
+--------------------+
| [email protected] |
| [email protected]  |
+--------------------+

Consider the 2 objects above, my goal objective is to check if a user exists in Object 2 and Object 1. If they exist in Object 2 then I want to return their ID value.

This code is where i'm up to, this will return the users who email address exists in both objects but not their ID:


$x = $object1 | Select-Object -ExpandProperty emailaddress
$y = $object2 | Select-Object -ExpandProperty email

$z = Compare-Object $x $y -IncludeEqual -ExcludeDifferent

$userids = @()

foreach($a in $z.inputobject){

    if($object2.email -contains $a){

        $userids += $a
    }
}

Attempt 2 based on Olaf's reply:

$object1 = New-Object -Typename psobject
$object1 | Add-Member -MemberType NoteProperty -Name email -Value $otherobject.members.email
$object1 | Add-Member -MemberType NoteProperty -Name id -Value $otherobject.members.id

$object2 = New-Object -Typename psobject
$object2 | Add-Member -MemberType NoteProperty -Name email -Value $otherobject2.emailaddress

$ComparedUsers = Compare-Object -ReferenceObject $object1 -DifferenceObject $object2 -IncludeEqual -ExcludeDifferent -PassThru

Upvotes: 1

Views: 169

Answers (1)

Olaf
Olaf

Reputation: 5252

You should not use -ExpandProperty when you want to use other properties of the object as well. And I'd recommend to use the same property names for both objects.

Something like this should push you to the right direction:

$object1 = 
@'
user,id,email
testuser,asfasfasdf,[email protected]
imatest,bsvxcffasd,[email protected]
other,lkjshfdlakjs,[email protected]
'@ |
    ConvertFrom-Csv
$object2 =
@'
email
[email protected]
[email protected]
[email protected]
'@ |
    ConvertFrom-Csv

Compare-Object -ReferenceObject $object1 -DifferenceObject $object2 -Property 'email' -IncludeEqual -ExcludeDifferent -PassThru

The output of that would be ...

user     id         email              SideIndicator
----     --         -----              -------------
testuser asfasfasdf [email protected] ==
imatest  bsvxcffasd [email protected]  ==

Upvotes: 1

Related Questions