我有以下代码,其中我试图检查一个组是否已存在于活动目录中。如果不存在,那么继续&创建组。但我的小组检查功能不正确。
你能提出一些建议吗?
以下是检查该组是否已存在的代码部分。
using (var domainContext = new PrincipalContext(ContextType.Domain, "xyz"))
{
var foundGrp = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, obj);
bool UserExists = (foundGrp != null);
if (!UserExists)
{
//DirectoryEntry group = entry.Children.Add("CN=" + obj, "group");
group.CommitChanges();
Console.WriteLine("AD Group " + obj + " has been created");
Console.WriteLine("=====================================");
}
}
这是我的整个代码。我只是尝试了几个功能。从长远来看,我会将我的代码模块化为单独的函数。感谢。
static void Main(string[] args)
{
try
{
/*Read the input XML File*/
XmlDocument xml = new XmlDocument();
xml.Load(@"xyz.xml");
var exportNode = xml.SelectSingleNode("//Export");
for (int i = 0; i < exportNode.ChildNodes.Count; i++)
{
/*Node 1 reads block 1 of the XML*/
XmlNode dataNode = exportNode.ChildNodes[i];
var environmentNode = dataNode.SelectSingleNode("env");
var tech_domainNode = dataNode.SelectSingleNode("Tech");
string env = environmentNode.InnerText;
string tech_domain = tech_domainNode.InnerText;
var output_valueNode = dataNode.SelectSingleNode("Output_Value");
string obj = output_valueNode.InnerText;
Console.WriteLine("obj is " + obj);
if (tech_domain == "AD Group")
{
string path = "LDAP://OU=Security,OU=Groups,DC=xyz";
using (DirectoryEntry entry = new DirectoryEntry(path))
{
DirectoryEntry group = entry.Children.Add("CN=" + obj, "group");
group.Properties["sAmAccountName"].Value = obj;
using (var domainContext = new PrincipalContext(ContextType.Domain, "xyz"))
{
var foundGrp = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, obj);
bool UserExists = (foundGrp != null);
if (!UserExists)
{
//DirectoryEntry group = entry.Children.Add("CN=" + obj, "group");
group.CommitChanges();
Console.WriteLine("AD Group " + obj + " has been created");
Console.WriteLine("=====================================");
}
}
}
}
else
{
Console.WriteLine("Technology Domain for " + obj + " is not an AD Group");
Console.WriteLine("====================================================");
}
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
Console.WriteLine("===============================");
}
}
}
}
答案 0 :(得分:0)
我认为你是以一种非常全面的方式进行的。请查看Everything in Active Directory via C#.NET。有三个系列的帖子描述了使用.NET System.DirectoryServices.AccountManagement命名空间来管理AD并对任何给定的主体执行CRUD操作。