Subscribe via Email

Subscribe via RSS/JSON


Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan


Finding groups a user belongs to, including nested groups

Two days ago I had posted about the AdminSDHolder object. Related to this issue I had to find whether a particular user account was a member of the ‘Account Operators’ group or not. It wasn’t a member directly, but it looked like it was a member via some nested group and I needed some way of figuring out how.

Option one was to do this manually. Sorry, that doesn’t work for me! So I used PowerShell to enumerate the groups and nested groups:

The code looks more complicated than it really is. That’s because I have also put it some logic to indent the output for nested groups. If you don’t care about all that here’s what the code looks like:

The key thing is the Get-ADPrincipalGroupMembership cmdlet which lists the groups an object is a member of. So all I do is get such a list and then run this cmdlet for each group in this list.

I tried to be smart here and use recursion. What I did is:

  1. Create a function called Get-Groups which takes an object as input and returns the groups its a member of.
  2. For each such group, Get-Groups calls itself with the group as an input – which results in a list of groups that group is a member of.
  3. And that’s it!

The code can be made neater I think but I haven’t coded in PowerShell for a while and have lost touch. Not good, I know … I wish I were using it regularly than occasionally. :-/


If you are interested in capturing the output to a file via an Out-File pipe for instance, that won’t work because Write-Host outputs to the console by default. Replace Write-Host in my code above with Write-Output and that will correctly output to console or pipe to Out-File. Thanks to one of my readers for pointing this out!

Finding groups a user belongs to, including nested groups by rakhesh is licensed under a Creative Commons Attribution 4.0 International License.