将启用的计算机添加到Active Directory OU

我正在尝试以编程方式将计算机添加到我公司的Active Directory中。
我现在在互联网上搜索这么久了,但我找不到解决办法。

我的代码:

DirectoryEntry dirEntry = new DirectoryEntry("LDAP://OU=ou2example,OU=ou1example,DC=site,DC=company,DC=com"); dirEntry.Username = "username"; dirEntry.Password = "password"; DirectoryEntry newComputer = dirEntry.Children.Add("CN=" + ComputerName, "computer"); newComputer.CommitChanges(); 

我的问题:

计算机已添加到Active Directory中。 但它被标记为已禁用。

在此处输入图像描述

我试着跟随启用计算机:

 newComputer.Properties["userAccountControl"].Value = 0x200; 

但我得到一个DirectoryServicesCOMException – >服务器无法完成请求。

要么

 newComputer.Properties["Enabled"].Value = true; 

但是我得到一个DirectoryServicesCOMException – >请求的操作不满足至少一个针对此对象类条件的约束。

请注意,例外情况从德语翻译成英语!

谢谢你的帮助!

我认为有两件事可能是错的,但是我做了这样的事情已经有很长一段时间了,所以我可能错了……

首先,你什么时候设置userAccountControl标志? 我似乎记得你应该在新条目的CommitChanges之后执行此操作。 像这样:

 DirectoryEntry newComputer = dirEntry.Children.Add("CN=" + ComputerName, "computer"); newComputer.CommitChanges(); newComputer.Properties["userAccountControl"].Value = 0x200; newComputer.CommitChanges(); 

其次,您可以尝试设置UF_WORKSTATION_TRUST_ACCOUNT标志( 0x1000 )而不是UF_NORMAL_ACCOUNT0x200 )。

您还可以检查条目的sAMAccountType是否为SAM_MACHINE_ACCOUNT0x30000001 )。 我认为这应该是自动的,但检查不会有害。

差不多一年后,还有一年更聪明,我确切地知道我做错了什么。

所以我想和你分享正确的方法,即使我已经选择了答案。

 DirectoryEntry dirEntry = new DirectoryEntry(“LDAP Path”); DirectoryEntry newComputer = dirEntry.Children.Add(“CN=Hostname”, “computer”); newComputer.Properties[“sAMAccountName”].Value = Hostname + “$”; newComputer.Properties[“UserAccountControl”].Value = 0x1020; newComputer.CommitChanges(); 

说明

sAMAccountName赋

解释在这里找到

计算机对象的sAMAccountName属性是附加了尾随美元符号“$”的计算机的NetBIOS名称。 除了将对象标记为计算机(具有类用户)之外,它还有助于确保唯一性。 sAMAccountName值在域中必须是唯一的。 注意,计算机对象的公共名称(cn属性的值)没有尾随的“$”,但cn也不能唯一地标识AD中的对象。 Common Name只需要在OU或容器中是唯一的。

机器帐户的sAMAccountName属性中始终会给出一个尾随的美元符号“$”; 这导致它们不被某些API枚举,因此不会显示在某些用户界面中,而这些用户界面只能看到“用户”帐户。

的UserAccountControl

UserAccountControl标志值