Reputation: 17
I am trying the following:
Variable1 = 'jack' , 'brody' , 'zack'
Variable2 = 'zack'
every value inside both variable1 and variable2 has the following attributes.
jack.username
jack.mail
jack.ou
I want compare variable1 with variable2 and only return users that are not present in variable2 and save the result to a new variable3.
"Example jack and brody would be returned to variable3, but not zack as he is present in both variable 1 and 2."
After return I also want username, mail and ou to be available in variable3.
I tried with the following:
$variable3 = $Variable1.SamAccountName | Where {$variable2.SamAccountName -
NotContains $_}
$variable3 = Compare-Object -ReferenceObject $variable1 -DifferenceObject
$variable2 -ExcludeDifferent
(second one does not return anything if excludedifferent is used).
Upvotes: 0
Views: 219
Reputation: 25001
You can use the following:
$variable3 = Compare-Object -ReferenceObject $variable1 -DifferenceObject $variable2 -Property SamAccountName -PassThru
When using Compare-Object, the -Property
parameter allows you to specify which property value you want to compare rather than comparing entire objects.
The -PassThru
switch returns all of the objects in their original form, which would include all of the properties you want.
Although not used here, the -ExcludeDifferent
switch will return nothing if not used with -IncludeEqual
because by default, Compare-Object
returns differences.
Alternatively, you can use a combination of comparison operators1 and Where-Object
. Since -contains
and -in
operator variants can support collections and single object comparisons, I would personally use those in favor of singular comparison operators like -eq
or -like
to ensure a more robust solution.
$variable3 = $variable1 | Where {$_.SamAccountName -notin $variable2.SamAccountName}
The object on the left side of the pipe |
contains the properties that will return after the Where-Object
is processed. So if you use $variable1.SamAccountName | Where
, you will only return SamAccountName
values.
[1]: Note that operators -notin
and -in
were added in PowerShell v3. If you are running PowerShell v2, they will not be available.
Upvotes: 1