$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
In this post I will show an easy way to get the recursive group membership for the current user.
I use this in a logon script to handle certain tasks based on group membership.
Most scripts I see for this task do a manual recursive enumeration but in a large environment this could be very slow.
A better way would be to use the tokenGroups attribute of the Active Directory user object.
The tokenGroups attribute is an array of SIDs computed by Active Directory and is used to verify user access.
We need to translate these SIDs to their sAMAccountNames to get the actual group names.
In unmanaged code this could be accomplished by calling the DsCrackNames API or the IADsNameTranslate interface.
In Powershell the easiest way is to use the UserPrincipal class (requires .NET Framework 3.5 or higher) which exposes the GetAuthorizationGroups method.
This makes it a very easy task. In the sample below I also use the where object to filter the results and the select object to return only the SamAccountName property.
1 2 3 4 5 6 7 8 | Add-Type -AssemblyName System.DirectoryServices.AccountManagement $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current $groups = $user.GetAuthorizationGroups() | where {$_ -like "S_APPS*"} | select SamAccountName foreach ($group in $groups) { $group } |
8 Responses for "Recursive group Membership in Powershell"
[…] Dit blogartikel was vermeld op Twitter door Don Jones. Don Jones heeft gezegd: RT @RemkoWeijnen: Blogged: #Powershell script to get recursive group membership http://bit.ly/f7Lqrs […]
But that’s only 1 level 🙂
@Michel: no it works for an unlimited number of levels, see my “proof” post: https://www.remkoweijnen.nl/blog/2011/01/18/recursive-groups-2/
[…] Jan In my previous post I explained how to get the recursive group membership with a very simple Powershell […]
Excellent work! Much more efficient than what I had cobbled together so far (old code was more than 41 lines just to return a group membership array). Thank you!
Only works for one level for me too.
Great thanks – exactly what I was looking for!
For those who want to do it for any user:
$name = “arosen” #SamAccountName
$assembly = [System.Reflection.Assembly]::LoadWithPartialName(“System.DirectoryServices.AccountManagement”)
$context = New-Object -typename “System.DirectoryServices.AccountManagement.PrincipalContext” -argumentlist $([System.DirectoryServices.AccountManagement.ContextType]::Domain)
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context,$([System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName),$name)
$user.GetAuthorizationGroups() | select SamAccountName
Leave a reply