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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Import-Module ActiveDirectory $level = 0 function Get-Groups ([string]$object) { if ($object.length -ne 0) { $groups = Get-ADPrincipalGroupMembership $object | select Name if ($groups -ne $null) { foreach ($group in $groups) { [string]$g = $group.Name; if ($level -ne 0) { for ($i = 0; $i -le $level; $i++) { write-host -NoNewline " " } } Write-Host "$g"; $level++; Get-Groups $g; $level-- } } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 |
Import-Module ActiveDirectory function Get-Groups ([string]$object) { if ($object.length -ne 0) { $groups = Get-ADPrincipalGroupMembership $object | select Name if ($groups -ne $null) { foreach ($group in $groups) { [string]$g = $group.Name; Write-Host "$g"; Get-Groups $g; } } } |
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:
- Create a function called
Get-Groups
which takes an object as input and returns the groups its a member of. - 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. - 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. :-/
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!