How can I about getting a user's group memberships from AD, preferably using the same pattern as I use to get the user's Department property, as below? I have found several examples, but the intersecting set of all example techniques is quite small, and lacks the tightness and simplicity of this Department query:
var adServer = ConfigurationManager.AppSettings["adServer"] ?? "localhost";
var remoteRoot = new DirectoryEntry(GetRootPath(adServer));
var searcher = new DirectorySearcher(remoteRoot, string.Format("(SAMAccountName={0})", shortUserName));
searcher.PropertiesToLoad.Add("Department");
SearchResult result = null;
result = searcher.FindOne();
Go to “Active Directory Users and Computers”. Click on “Users” or the folder that contains the user account. Right click on the user account and click “Properties.” Click “Member of” tab.
Run Netwrix Auditor → Navigate to "Reports" → Expand the "Active Directory" section → Go to "Active Directory - State-in-Time" → Select "User Accounts - Group Membership"→ Click 'View". To save the report, click the "Export" button → Choose a format from the dropdown menu → Click "Save".
To get (sorted) plain list of groups only, you can run (New-Object System. DirectoryServices. DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")). FindOne().
Are you on .NET 3.5 ? If so, it's very easy:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
string userName = "yourUser";
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);
PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();
Find your user, and then call the .GetAuthorizationGroups()
on your user principal - that returns all groups the user belongs to, including his primary group, and any nested group memberships.
Check out this MSDN article for more new goodness in .NET 3.5 when it comes to dealing with AD.
In .NET 2.0, things are a lot messier...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With