The other day I needed to know the Active Directory groups a user had assigned. Not being an operations person, I couldn’t go and use the tools on the server. I decided there must be an easy way to get this done. After a bit of searching, I came up with this LinqPad script using some assemblies Microsoft provided.
Assemblies:
System.DirectoryServices
System.DirectoryServices.ActiveDirectory
System.DirectoryServices.AccountManagement
System.DirectoryServices.Protocols
string username = 'hlord'; string domain = 'MyDomain'; var domainGroups = new List<string>(); var domainContext = new PrincipalContext(ContextType.Domain, domain); var user = UserPrincipal.FindByIdentity(domainContext, username); var authGroups = user.GetAuthorizationGroups(); authGroups.All(g => { if (!string.IsNullOrEmpty(g.Name) && !domainGroups.Contains(g.Name)) domainGroups.Add(g.Name); return true; }); domainGroups.Sort(); domainGroups.Dump();
LinqPad File: LDAP – User Groups.linq