I have been asked to generate a list of the security groups (so specifically not the distribution groups) that a list of approximately 50 users belong to.
I have a list of users, users.txt
that contains each username on a new line. I want to generate a membership.txt
that contains the username and a list of the security groups that user is a member of, separated by commas.
The Powershell script I have written so far is as follows:
$users = Get-Content C:\users.txt
ForEach ($User in $users) {
$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof
$User + ',' + $getmembership | Out-File -Append c:\membership.txt
}
This almost works, but for two problems:
- It is generating a list of all groups, not just security groups. How can I tell it to only include security groups and not distribution groups?
- The groups are being appended in the format
OU=Security Groups,OU=City,DC=domain,DC=com CN=Senior Leaders
, but the only information I actually want isSenior Leaders
. How can I cut out all the extra information?
Extend your
Get-ADUser
line:This will feed the DN of the Group to
Get-ADGroup
to retrieve additional properties, then filter on group category and select the name of the group (instead of the DistinguishedName).