1

新しい 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) {

}

しかし、例外が発生しますサーバーにそのようなオブジェクトはありません。

任意の助けをいただければ幸いです。

4

1 に答える 1

3

entry.Children.Find()aがディレクトリ全体を再帰的に検索するという (誤った) 仮定の下にあるようです- それはしません

したがって、そのグループが配置されるべき実際のコンテナーにバインドする必要があり、次に、グループの存在についてその直下の子を確認します。

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
}
于 2013-06-21T10:58:33.880 に答える