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
CodePudding user response:
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))"
}
)
CodePudding user response:
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