簡體   English   中英

C#將PC添加到AD域組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM