[英]Check if Active Directory Group exists in current container using C#
I want to create a new Active Directory Group. 我想创建一个新的Active Directory组。
This is my code: 这是我的代码:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, container, userName, password);
GroupPrincipal oGroupPrincipal = new GroupPrincipal(ctx, userName);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password,AuthenticationTypes.Secure);
if (entry.Children.Find("CN=" + groupName) != null) {
}
if (!DirectoryEntry.Exists("LDAP://" + System.Configuration.ConfigurationManager.AppSettings["Domain"] + "/CN=" + groupName + "," + System.Configuration.ConfigurationManager.AppSettings["Container"]))
{
oGroupPrincipal.Description = groupName;
oGroupPrincipal.GroupScope = (System.DirectoryServices.AccountManagement.GroupScope)Enum.Parse(typeof(System.DirectoryServices.AccountManagement.GroupScope), groupScope);
oGroupPrincipal.IsSecurityGroup = isSecurity;
oGroupPrincipal.Save(ctx);
}
The Part that I am having trouble with is to see if the newly created group exists before creating it. 我遇到问题的部分是在创建它之前查看新创建的组是否存在。 At this stage my code returns that al the groups exists so I am unable to create a group
在这个阶段,我的代码返回组存在,所以我无法创建组
This is to check if group exists: 这是为了检查组是否存在:
if (entry.Children.Find("CN=" + groupName) != null) {
}
but it gives an exception There is no such object on the server. 但它给出了一个例外服务器上没有这样的对象。
any help would be appreciated. 任何帮助,将不胜感激。
You seem to be under the (false) assumption that a entry.Children.Find()
will do a recursive search through your entire directory - it does not do that. 你似乎是(假)假设下,一个
entry.Children.Find()
将通过您的整个目录执行递归搜索-它没有做到这一点。
So, either you need to bind to the actual container where that group should be located, and then check its immediate children for existence of your group: 因此,您需要绑定到该组所在的实际容器,然后检查其直接子项是否存在您的组:
DirectoryEntry entry = new DirectoryEntry("LDAP://YourServer/OU=SubOU,OU=TopLevelOU,dc=test,dc=com", userName, password,AuthenticationTypes.Secure);
try
{
DirectoryEntry childGroup = entry.Children.Find("CN=TestGroup2");
// create group here
}
catch (DirectoryServicesCOMException exception)
{
// handle the "child not found" case here ...
}
or then you need to do a directory search for your group which works recursively through your entire directory (and thus will be much slower , too): 或者你需要对你的组进行目录搜索 ,它在整个目录中以递归方式工作(因此也会慢很多 ):
// define root directory entry
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + domain, userName, password,AuthenticationTypes.Secure);
// setup searcher for subtree and search for groups
DirectorySearcher ds = new DirectorySearcher(domainRoot);
ds.SearchScope = SearchScope.SubTree;
ds.Filter = "(&(cn=TestGroup2)(objectCategory=group))";
var results = ds.FindAll();
if(results.Count <= 0)
{
// group not found -> create
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.