Windows – How to Generate a List of Security Groups for Users

active-directorygroupspowershellwindows

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:

  1. 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?
  2. 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 is Senior Leaders. How can I cut out all the extra information?

Best Answer

Extend your Get-ADUser line:

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof | Get-ADGroup -Properties name | Where { $_.GroupCategory -eq 'Security' } | Select -ExpandProperty Name

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).