繁体   English   中英

使用C#检查当前容器中是否存在Active Directory组

[英]Check if Active Directory Group exists in current container using C#

我想创建一个新的Active Directory组。

这是我的代码:

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);
}

我遇到问题的部分是在创建它之前查看新创建的组是否存在。 在这个阶段,我的代码返回组存在,所以我无法创建组

这是为了检查组是否存在:

if (entry.Children.Find("CN=" + groupName) != null) {

}

但它给出了一个例外服务器上没有这样的对象。

任何帮助,将不胜感激。

你似乎是(假)假设下,一个entry.Children.Find()将通过您的整个目录执行递归搜索-它没有做到这一点。

因此,您需要绑定到该组所在的实际容器,然后检查其直接子项是否存在您的组:

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 ...
}

或者你需要对你的组进行目录搜索 ,它在整个目录中以递归方式工作(因此也会慢很多 ):

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM