6

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?
NaOH
  • 411
  • 2
  • 10
  • 19

1 Answers1

6

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

Oliver Rahner
  • 287
  • 1
  • 8
  • This appears to return almost no groups... I see mostly this: `username, username, username,@{Name=Group} username, username, username,@{Name=Different Group}` – NaOH Sep 25 '14 at 19:48
  • Sorry, missed an `ExpandProperty`, corrected. – Oliver Rahner Sep 25 '14 at 20:36
  • Sorry, the only thing that's not working is comma-separating the groups. Lots of our groups have spaces in the names so I can't rely on spacing to parse the groups out. I can't work out the syntax to add a comma between each group. – NaOH Sep 25 '14 at 20:41
  • Simple: `$User + ',' + ($getmembership -join ',')` – Oliver Rahner Sep 25 '14 at 20:45