0

I'm writing a script to get a list of the current user's AD Groups and creates a .txt file to a Path.

I've had a look around and it seems like I should be using these references:

using System.DirectoryServices; using System.DirectoryServices.AccountManagement;

I'm also using this:

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, "<Domain>"), IdentityType.SamAccountName, "<UserName>");
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group);
}

But this doesn't quite list all the groups that the user should be in.

Is there something I'm missing?

Justin
  • 954
  • 4
  • 22
  • 44
  • Check out https://stackoverflow.com/questions/5309988/how-to-get-the-groups-of-a-user-in-active-directory-c-asp-net – Andrew Drake Apr 20 '18 at 12:27

1 Answers1

1

I use this block of code to get the user groups:

        String domainName = @"<your domain>";
        String username = domainName + @"\<your username>";
        PrincipalContext thisDomain = new PrincipalContext(ContextType.Domain);

        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(thisDomain, username);

        PrincipalSearchResult<Principal> userGroups = userPrincipal.GetAuthorizationGroups();

        foreach (Principal principal in userGroups.OfType<GroupPrincipal>())
        {
            Debug.WriteLine(principal.Name);
        }

As far as I can tell, it lists all the groups the user is a member of by comparison to what is held in Active Directory and looking at the user object in the MMC snap in

JayV
  • 3,238
  • 2
  • 9
  • 14
  • Doing a comparison between the two methods, with mine I get 21 extra groups being listed at my companies Forest/Domain/AD setup. Don't know why the differences exist though. – JayV Apr 20 '18 at 12:42