简体   繁体   中英

C# Console Application - Get Current User AD Groups

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM