Powershell: get list of users and their groups
The Powershell objects for AD users contain a calculated attribute, MemberOf. If you want to merely get the names of said groups, and not the DNs, as an attribute of the users, you will have to transform the objects with more than a one-liner.
$results = Get-ADUser -SearchBase 'OU=Users,DC=example,DC=com' -LDAPFilter "(EmployeeID=*)" -Properties EmployeeID, GivenName, Surname, EmailAddress, Manager, Department, physicalDeliveryOfficeName, Title, Mobile, MemberOf, UserPrincipalName, PrimaryGroup, SamAccountName, displayName, country, departmentNumber, adminDisplayName, LockedOut, Enabled | ? { $_.enabled -eq $True }
$x = 0
$xtotal = $results.count
$out = ForEach ($tu in $results) {
$x = $x + 1
if ( ($x/50) -eq [int]($x/50) ) { Write-Progress -Activity "Enumerating groups for each user" -PercentComplete ($x/$xtotal*100) }
$groups = ForEach($tg in $tu.MemberOf) { (Get-ADGroup $tg).Name } ;
$groupStr = $groups -join ":" ;
$tu | Select-Object EmployeeID, GivenName, Surname, EmailAddress, Manager, Department, physicalDeliveryOfficeName, Title, Mobile, UserPrincipalName, PrimaryGroup, SamAccountName, displayName, country, departmentNumber, adminDisplayName, LockedOut, Enabled,@{n='Groups';e={$groupStr} ;
} ;
}
Which you can then export to a csv file.
$out | Export-Csv Users.csv
Addenda
Go ahead, and tell me that I can include the enabled filter in the -LdapFilter parameter. I didn't feel like looking up the complicated bitmask comparison required for that. Microsoft stores Enabled=True in ldap in a complex object attribute.
References
Weblinks
- Ripped mostly from [SOLVED] Format memberof attribute - PowerShell - Spiceworks
- write-progress syntax Using Write-Progress to provide feedback in Powershell
Comments