On3N3xus
On3N3xus

Reputation: 11

Compare Object and exporting an Excel Spreadsheet with only users that are in both AD groups

I'm wanting this script to export an Excel spreadsheet with only the users that are in both AD groups.

$members1 = (Get-ADGroup 'Imprivata1' -Properties Member).Member $members2 = (Get-ADGroup 'Imprivata2' -Properties Member).Member

Compare-Object $members1 $members2 -IncludeEqual | Sort-Object Name | Export-Csv "C:\users$env:username\Desktop\compareadgroups.csv" -Encoding UTF8 -NoTypeInformation

Upvotes: 0

Views: 211

Answers (2)

js2010
js2010

Reputation: 27516

Restricting the output to equal ones only using the sideindicator property, and there's no name property, but inputobject is the property to sort. Powershell 7 not powershell 5.1's export-csv has a -usequotes parameter.

compare $members1 $members2 -includeequal | ? sideindicator -eq == |
  sort inputobject | export-csv -notype -usequotes asneeded compareadgroups.csv

Upvotes: 0

Toni
Toni

Reputation: 1826

you do not need to use compare-object, you can simply query AD for users which are in both groups:

#Get Group distinguishedName
$groupDNs = get-adgroup -ldapfilter "(|(samaccountname=Imprivata1)(samaccountname=Imprivata2))"

#Build ldap filter
$ldapArray = @(
    $groupDNs | %{
        "(memberof=$($_.distinguishedName))"
    }
)
$ldapString = $ldapArray -join $null

#Search Users that are member of both groups
$users = Get-ADUser -ldapfilter "(&$ldapstring)"

#Recursive Version of the ldap filter
$ldapArray = @(
    $groupDNs | %{
        "(memberof:1.2.840.113556.1.4.1941:=$($_.distinguishedname))"
    }
)

Upvotes: 0

Related Questions