Powershell – Comparing two specific properties of a CSV using Compare-Object isn’t giving the expected results

powershell

I have a list of users from two separate domains. These lists are in CSV format and I only care about the SAMAccountName, which is a field in these CSVs.

The code that I'm working with is currently:

$domain1 = Import-CSV C:\Scripts\Temp\domain1.xxx.org.csv | Select-Object SAMAccountName
$domain2 = Import-CSV C:\Scripts\Temp\domain2.xxx.org.csv | Select-Object SAMAccountName

Compare-Object ($domain1) ($domain2)

This is returning only a handful of results (which aren't accurate) in this format:

@{samaccountname=SomeUser}                                       =>

Obviously, Compare-Object isn't evaluating the objects as strings. How do I make this work?

Best Answer

Given the example CSV file "domain1.xxx.org.csv", with contents as:

"name","samaccountname","description","distinguishedname","enabled","lastlogondate" 
"ADAUser01","ADAUser01",,"CN=ADAUser01,OU=Users,OU=ADA,DC=phl,DC=xxx,DC=ORG","True","8/7/2012 2:28:37 PM"

We can see how Import-Csv converts the text into a PSCustomObject using the headings:

Import-Csv domain1.xxx.org.csv | Select-Object -First 1 | Get-Member

   TypeName: Selected.System.Management.Automation.PSCustomObject

Name              MemberType   Definition
----              ----------   ----------
Equals            Method       bool Equals(System.Object obj)
GetHashCode       Method       int GetHashCode()
GetType           Method       type GetType()
ToString          Method       string ToString()
description       NoteProperty System.String description=
distinguishedname NoteProperty System.String distinguishedname=CN=ADAUser01,OU=Users,OU=ADA,DC=phl,DC=xxx,DC=ORG
enabled           NoteProperty System.String enabled=True
lastlogondate     NoteProperty System.String lastlogondate=8/7/2012 2:28:37 PM
name              NoteProperty System.String name=ADAUser01
samaccountname    NoteProperty System.String samaccountname=ADAUser01

Filtering this via Select-Object SAMAccountName results in the following:

Import-Csv domain1.xxx.org.csv | Select-Object -First 1 SamAccountName

   TypeName: Selected.System.Management.Automation.PSCustomObject

Name           MemberType   Definition
----           ----------   ----------
Equals         Method       bool Equals(System.Object obj)
GetHashCode    Method       int GetHashCode()
GetType        Method       type GetType()
ToString       Method       string ToString()
samaccountname NoteProperty System.String samaccountname=ADAUser01

If you want to compare the NoteProperty across two PSCustomObjects, because we're not just evaluating a String, you'll just need to tell Compare-Object which Property you want to compare with:

Compare-Object $domain1 $domain2 -Property SamAccountName