[英]C# Adding PC to AD domain group
尝试将主机名添加到域组,但出现异常There is a naming violation
。
据我所知我的语法是正确的,我已经看到了几个关于此确切内容的公认答案。
try
{
DirectoryEntry de = new DirectoryEntry("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Groups,OU=US,DC=aa,DC=bbbbb,DC=com");
string hostname = "CN=" + SystemInformation.ComputerName;
DirectoryEntry add = de.Children.Add(hostname, "Computer");
add.CommitChanges();
}
catch (Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
任何帮助将不胜感激。
我弄清楚了问题所在-我需要传递专有名称,而不只是主机名...如果我已经阅读了MSDN文档,那应该很明显...此外, de.Children.Add()
可能是实现此目的的一种有效方法(对于.Net 3.5 IIRC,这是SE上的一个可接受的答案),但我使用了de.Properties["member"].Add()
来实现。
已更新的任何Google员工的源代码:
private void DoStuff(object sender, EventArgs e)
{
using (Process addgroup = new Process())
{
string hostname = Environment.MachineName;
AddMemberToGroup("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Group,OU=US,DC=aa,DC=bbbbb,DC=com", hostname);
}
}
private void AddMemberToGroup(string ldapString, string host)
{
try
{
DirectoryEntry de = new DirectoryEntry(ldapString);
string distHost = GetDistinguishedName(host);
if (!String.IsNullOrEmpty(distHost))
{
de.Properties["member"].Add(distHost);
de.CommitChanges();
}
else
{
MessageBox.Show("Distinguished Host Name returned NULL");
}
}
catch(Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
}
private string GetDistinguishedName(string compName)
{
try
{
PrincipalContext pContext = new PrincipalContext(ContextType.Domain);
ComputerPrincipal compPrincipal = ComputerPrincipal.FindByIdentity(pContext, compName);
return compPrincipal.DistinguishedName;
}
catch (Exception ex)
{
MessageBox.Show("Failed to get the Distinguished Hostname from Active Directory" + Environment.NewLine + Environment.NewLine + ex.ToString());
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.