Reputation:
I am currently trying to pull all of the users in my organization from a security group called Y under a security group called X. I have tried multiple different approaches to this and am starting to reach my wits end with it. I am currently back to the DirectoryEntry method of trying to retrieve my users, but was previously trying the PrincipalContext method. The PrincipalContext method works very well for retrieving my servers, but they are members of singular top-level groups. Group Y is nested under group X which is grouped like so: A -> B -> C -> D -> X -> Y. Another possible problem I see is the distinguishedName property has the OUs in what appears to be an unorganized manner so I'm sensing the order doesn't matter when it comes to AD? But I would assume when querying with wild cards the order somewhat matters?
The distinguishedName property is structured like so (pseudo to save typing): CN=User Name, OUs=Y, D, X, C, B, A, DCs=a, b, c, net
Below is my current code to pull users:
private static void GetUsers() {
int x = 0;
DirectoryEntry dm = new DirectoryEntry("LDAP://a.b.c.net");
DirectorySearcher searcher = new DirectorySearcher(dm);
searcher.Filter = "(&(objectClass=user)(distinguishedName=*OU=Y*OU=X*))";
searcher.PropertiesToLoad.AddRange(new string[4] {"name", "samAccountName", "userPrincipalName", "mail"});
foreach (SearchResult result in searcher.FindAll()) {
Console.WriteLine(string.Format("Name: {0}\nSAM: {1}\nPrincipal: {2}\nMail: {3}",
result.Properties["name"],
result.Properties["samAccountName"],
result.Properties["userPrincipalName"],
result.Properties["mail"]));
x++;
}
Console.WriteLine("User Count: " + x);
}
I am assuming this is an issue with my filter since the code executes completely and prints a user count of zero. I am finding it hard to understand how the wild card works and have found very little information on how to pull users from sub-groups and to narrow things down. I work for a very, very, large organization so just pulling all users in the domain would not only take a lot of time, but would also return tens of thousands of records.
Please help?!?!?!?!? -Thanks, Jamie
Upvotes: 1
Views: 937
Reputation:
So after hours of research and no luck here on Stack Overflow, I figured out that it was a combination of my domain and filter. I had to add the OU list to the end of the DNS in the supplied domain. Also, the filter needed to be narrowed down and I had to removed the distinguishedName property and just filter the name and sn properties.
using (DirectoryEntry entry = new DirectoryEntry("LDAP://a.b.c.net/OU=Y,OU=D,OU=X,OU=C,OU=B,OU=A,DC=a,DC=b,DC=c,DC=net"))
mySearcher.Filter = ("(&(objectClass=user)(&(|(name=*1*)(name=*2*))(!(sn=*.*))))");
Upvotes: 2