Search code examples
powershellactive-directorycommand-behaviors

How can I get the different object between two two element datasets?


If I have these two files containing the following datasets:

OldFile:

"CanonicalName","LastSet"
"CONTOSO.com/NA/US/OU1/Users/Active/Test User","2019-07-02 14:14:44"
"CONTOSO.com/NA/US/OU1/Users/Active/User One","2019-07-02 14:14:44"
"CONTOSO.com/NA/US/OU2/Users/Active/User Two","2018-09-02 05:53:35"
"CONTOSO.com/OC/AU/OU3/Users/User Three","2017-06-23 14:20:07"

TempFile:

"CanonicalName","LastSet"
"CONTOSO.com/NA/US/OU1/Users/Active/User One","2019-07-02 14:14:44"
"CONTOSO.com/NA/US/OU2/Users/Active/User Two","2018-09-02 05:53:35"
"CONTOSO.com/OC/AU/OU3/Users/User Three","2017-06-23 14:20:07"

That returns:

InputObject                                                                                  SideIndicator
-----------                                                                                  -------------
@{CanonicalName=CONTOSO.com/OC/AU/OU3/Users/User Three; LastSet=2017-06-23 14:20:07} <=

Where I would have expected it to return the TEST user with "<=" when the following code is executed:

Compare-Object -ReferenceObject (import-csv $oldfile) -DifferenceObject (import-csv $tempfile) 

Why? How can I get the desired output? The DIFFERENT object.


Solution

  • Import-Csv will return an array of PSCustomObject that has properties called CanonicalName and LastSet.

    When Compare-Object has to compare complex objects with properties, you need to use the -Property parameter to tell it which properties to compare when testing for equality:

    Compare-Object -ReferenceObject (Import-Csv $oldfile) -DifferenceObject (Import-Csv $tempfile) -Property CanonicalName,LastSet
    

    The result is then:

    CanonicalName                                LastSet             SideIndicator
    -------------                                -------             -------------
    CONTOSO.com/NA/US/OU1/Users/Active/Test User 2019-07-02 14:14:44 <=