Check if a user is in a OU
By Anatoly Mironov
To get all users from an AD group is very simple:
groupName = "an\_ad\_group";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);
var principals = grp.GetMembers(true);
```But what about an OU? There is no OrganizationUnitPrincipal... [Well, there is a solution: to instantiate a context for your OU](http://stackoverflow.com/a/1927476/632117 "See the solution on Stack Overflow"): So if you want to check if a user in a OU:
internal static bool IsUserInOu(string ou, string name) { var domain = “takana.local”; var container = string.Format(“OU={0}, DC=takana, DC=local”, ou); var ctx = new PrincipalContext(ContextType.Domain, domain, container); var up = new UserPrincipal(ctx); var ps = new PrincipalSearcher(up);
var results = ps.FindAll();
return results.Any(p => p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
}