c# - Active Directory - Find a computer in a group -
i trying simple ad query see if computer in group. following code seems intuitive enough not work. ldapstring distinguised name group computer referenced netbiosname memberof.
public bool iscomputerinadgroup(string ldapstring, string netbiosname) { using (directoryentry entry = new directoryentry(string.format(@"ldap://{0}", ldapstring))) using (directorysearcher computersearch = new directorysearcher(entry)) { computersearch.filter = string.format("(&(objectcategory=computer)(cn={0}))", netbiosname); searchresult match = computersearch.findone(); if (match != null) { return true; } } return false; }
can please explain why incorrect , correct/fastest way to perform search is.
thanks p
your basic assumption wrong - computer (or user) cannot in group implying "containment" inside group; user or computer inside ou.
a user or computer can member of number of groups - need check against member property of group (or memberof attribute of element member of group).
so easiest way, really,
- bind object in question
- refresh property cache latest entries in
memberof
- enumerate of
memberof
entries , see if group you're looking present
something like:
public static bool isaccountmemberofgroup(string account, string group) { bool found = false; using (directoryentry entry = new directoryentry(account)) { entry.refreshcache(new string[] { "memberof" }); foreach (string memberof in entry.properties["memberof"]) { if (string.compare(memberof, group, true) == 0) { found = true; break; } } } return found; }
call so:
bool ismemberof = isaccountmemberofgroup("ldap://cn=yourcomputer,dc=corp,dc=com", "cn=yourgroupinquestion,ou=someou,dc=corp,dc=com");
and should fine.
update: if you're on .net 3.5, use new system.directoryservices.accountmanagement
namespace , linq make things easier:
public static bool isaccountmemberofgroup2(principalcontext ctx, string account, string groupname) { bool found = false; groupprincipal group = groupprincipal.findbyidentity(ctx, groupname); if (group != null) { found = group.getmembers() .any(m => string.compare(m.distinguishedname, account, true) == 0); } return found; }
and call this:
// establish default domain context principalcontext domain = new principalcontext(contexttype.domain); // call function bool ismemberof = isaccountmemberofgroup2(domain, "cn=yourcomputer,dc=corp,dc=com", "cn=yourgroupinquestion,ou=someou,dc=corp,dc=com");
Comments
Post a Comment