Powershell – Find users belonging to more than one AD group

active-directorypowershell

I'm new to AD and Powershell so please forgive me if I use the wrong terminology.

I have a series of 50+ Active Directory groups called "ABC-something". Every active user needs to belong to exactly one group.
Users are also members of other groups that are used for different purposes and that should not affect this exercise.

Since we're in the middle of a big move, my population is a moving target. I'm dealing with around 1000 users, so going through an export of all the memberships for all users is less than desirable.

I'm hoping to be able to write a script that will return the userid (or samAccountName) of every user that is a member of more than one group ABC* that I could run on demand.
(I assume writing a script to find active AD users NOT in a group is a different question altogether.)

Putting on my database hat, I see the logic as follows:

1) Iterate trough all groups called ABC*. For each, capture all group members.
I should end up with a table or object in memory looking like

Group1 PersonA
Group1 PersonB
Group2 PersonB

2) Find a way to group, or count, or iterate through this list.

This is where I get stuck because the Powershell examples I've seen so far don't manipulate the data much before exporting or displaying data.

Can you suggest a sample script to get me started, or at least point to online resources about manipulating data in Powershell?

Best Answer

Using Get-ADUser -Filter * -Properties memberOf gets a list of all users, and the groups they are a member of.

You could pipe that into a foreach or where-object and apply any required criteria. If you wanted to know if a user was in foo, and bar you could run a command like this.

Get-ADUser -Filter * -Properties memberOf | `
Where-Object {
    $_.memberof.contains('CN=foo,OU=allsites,DC=example,DC=org') -and `
    $_.memberof.contains('CN=bar,OU=allsites,DC=example,DC=org' ) 
}

Or lets say you just wanted to know how many people were in at least 7 groups?

Get-ADUser -Filter * -Properties memberOf | `
Where-Object {$_.memberof.count -ge 7}