开发者

Get users from Acctive Directory Group

开发者 https://www.devze.com 2023-02-02 10:20 出处:网络
I created an Active Directory domain name \'ADDOMAIN2\' having a group name \"CommonUsers\" having 8 users. but when I do a Direc开发者_高级运维tory Search for users in group \"CommonUsers\" it return

I created an Active Directory domain name 'ADDOMAIN2' having a group name "CommonUsers" having 8 users. but when I do a Direc开发者_高级运维tory Search for users in group "CommonUsers" it returns zero result. hers is my code

       DirectorySearcher searcher = new DirectorySearcher();
        DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("LDAP://{0}", "ADDOMAIN2"), "Administrator", "p@S$w0rd");
        string dnPath = directoryEntry.Properties["distinguishedName"].Value.ToString();

       // string path = string.Format("LDAP://{0}/{1}{2}", "ADDOMAIN2", "", dnPath);
        string path = "LDAP://ADDOMAIN2/CN=CommonUsers,DC=ADDomain2,DC=ADDomain01,DC=WaveDomain";
        directoryEntry.Path = path;
        searcher.SearchRoot = directoryEntry;
        searcher.Filter = "(&(objectCategory=person)(objectClass=user))";
        SearchResultCollection rs = searcher.FindAll();

Any Idea what is wrong here?

Thanx


Try using some external LDAP browser (like the old and free version 2.6 of Softerra LDAP Browser) to check whether your query string is really pointing to the correct location.


DirectorySearcher is not used to find users inside a group. It's used to find objects under a base path. Since there is no user objects placed under your AD group object, you won't find anything.

In most cases, you can find the user objects in an AD group from its member attribute. Beware that AD group can contain either group or user. So, some of the entres there may be group. In some cases, the member attribute does not contain AD group nor AD user, it's containing a Foreign Security Principal. This happens if your user is coming from another forest. The primary group is also handled differently. Even "Domain User" is primary group of most of the users in AD, its member attribute doesn't contain anything at all. There are a lot other oddities that makes enumerating an AD group object really hard.

Fortunately, in .NET 3.5, Microsoft provides some useful classes in the framework to do the dirty work for you. Check out System.DirectoryServices.AccountManagement

To get some quick examples, you can check out this codeproject article

Your code should be something like this.

PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com");
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Users");
foreach (Principal principal in groupPrincipal.GetMembers(false))
{
     Console.Out.WriteLine(principal.DistinguishedName);
}
Console.In.ReadLine();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号