简体   繁体   中英

How to compare the results of Get-ADUser?

I have the results of two Get-ADUser queries stored in variables (they are querying two Active Directories).

What is the best way to compare them looking for an specific attribute and export to a CSV if they match? I tried to get it to work using nested forEach loops and comparing attributes with an if but it just appended to the csv all the results from both AD.

I am not currently home and I will upload my current code when I arrive but in pseudocode it was like this:

$res1 = get-adUser -filter{enabled -eq $true} -Properties     samAccountName, displayname, mail | select-object samAccountName, displayname, mail
$res2 = get-adUser -server ABC -filter{enabled -eq $true} -Properties samAccountName, displayname, mail | select-object samAccountName, displayname, mail

ForEach($u1 in $res1){
  ForEach($u2 in $res2){
    If($u1.mail -eq $u2.mail){
      Write-host $u1.mail $u2.mail
    }
  }
}
Compare-Object -ReferenceObject $res1 -DifferenceObject $res2 -IncludeEqual -ExcludeDifferent

While you're exporting the same set of properties you can use Compare-Object for this:

$props = @("samAccountName","displayName","mail")
$res1 = Get-ADUser -filter 'GivenName -eq "Robert"' -properties $props | Select-Object $props
$res2 = Get-ADUser -filter 'GivenName -like "Rob*"' -properties $props | Select-Object $props
$comp = Compare-Object -ReferenceObject $res1 -DifferenceObject $res2 -IncludeEqual -ExcludeDifferent

By default, Compare-Object shows you differences between object so you have to include equal objects and exclude different ones.

If for some reason, you don't want to compare all the properties you can specify -Property parameter like this:

# In that example you you want compare only displayName and mail
# SamAccountName might be different
$comp = Compare-Object -ReferenceObject $res1 -DifferenceObject $res2 -IncludeEqual -ExcludeDifferent -Property displayName,mail

Note:

As you might have noticed, I added one more improvement to your script - I saved all the properties to variable and then used it in Get-ADUser and Select-Object (idea taken from this answer ). It might be useful if you want to add/remove any property. You can also do it like this:

$props = "samAccountName","displayName","mail"

But that only works for more than one parameter so I like to explicitly make it an array (more about this in another helpful answer ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM