簡體   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