/// <summary> /// Checks to see if the given OU has a child with the given name. Also, can check for a particular type of object as well. /// </summary> /// <param name="parentOU">The location where the search will occur.</param> /// <param name="childName">The name of the child object to look for. Case insensitive.</param> /// <param name="type">Optional. The specific type of object to look for.</param> /// <returns></returns> public static bool OUHasChildNamed(string parentOU, string childName, ADSchemaTypes? type = null) { using (var ou = new DirectoryEntry($"LDAP://{parentOU}", Properties.Resources.DomainAccount, Properties.Resources.domain)) { foreach (DirectoryEntry curOU in ou.Children) using (curOU) { //wrong named child. move on... if (!string.Equals(curOU.Properties["name"].Value.ToString(), childName, StringComparison.CurrentCultureIgnoreCase)) continue; if (type != null) { //named child found, return whether it's the type specified. return curOU.SchemaClassName == type.Value.ToString(); } //correctly named child found, non type-specific. return true; } return false; } }
/// <summary> /// Gets the names of the children of the parent OU. Optionaly of particular type. /// </summary> /// <param name="parentOU">The DN of the parent OU.</param> /// <param name="type">The type of object whose names to return.</param> /// <returns></returns> public static List<string> OUChildrenNames(string parentOU, ADSchemaTypes? type) { using (var ou = new DirectoryEntry($"LDAP://{parentOU}", Properties.Resources.DomainAccount, Properties.Resources.domain)) { var childrenNames = new List<string>(); foreach (DirectoryEntry curOU in ou.Children) using (curOU) { if (type.HasValue) { if (string.Equals(curOU.SchemaClassName, type.Value.ToString(), StringComparison.CurrentCultureIgnoreCase)) { childrenNames.Add(curOU.Properties["name"].Value.ToString()); } } else { childrenNames.Add(curOU.Properties["name"].Value.ToString()); } } return childrenNames; } }