2017-07-26 89 views
1

我有在C#创建通过LDAP电脑问题:C#创建在Active Directory中的计算机 - 小学组问题

以下是我的代码:

C#

string connectionPrefix = "LDAP://" + ldapPath; 

DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix, GlobalVar.adUser, GlobalVar.adUserPassword); 

DirectoryEntry newComputer = dirEntry.Children.Add("CN=" + computerName, "computer"); 
newComputer.Properties["samaccountname"].Value = computerName; 
newComputer.Properties["dnshostname"].Value = computerName + ".[privacy].[domain].[here]"; 
newComputer.Properties["description"].Value = GlobalVar.adUser; 
newComputer.Properties["location"].Value = "IT"; 

这完美的作品但有一个例外:计算机是在正确的文件夹中创建的。但是,当我直接在AD中创建计算机时,主要组是“域用户”而不是“域计算机”,则计算机会自动分配主组“域计算机”

结果是我无法将计算机添加到该域名无需在广告中手动修改。

任何解决方案?

最好的问候,

朱利安

+0

您使用的是.net 3.5或以上版本? – TonyW

+0

我确实使用.Net 4.5 –

回答

1

我会用System.DirectoryServices.AccountManagement做到这一点..

LDAPusername =具有编辑LDAP权限的用户名。

一旦创建了计算机名称,然后通过该组。

对不起,如果这不是完美的,这是我转换的vb.net代码。

//The following code changes the principal group of an existing computer 
PrincipalContext pc1 = new PrincipalContext(
    ContextType.Domain, 
    "subdomain.domain.com", 
    LDAPusername, 
    LDAPpassword 
); 
dynamic cp = ComputerPrincipal.FindByIdentity(pc1, "computername"); 
dynamic computer = (DirectoryEntry)cp.GetUnderlyingObject(); 
// distinguishedname = "CN=Domain Users,CN=Users,DC=domain,DC=com" 
string @group = "groupdistinguishedname"; 
DirectoryEntry groupdirentry = new DirectoryEntry(
    "LDAP://" + @group, 
    LDAPusername, 
    LDAPpassword 
); 
groupdirentry.Invoke("Add", new object[] { computer.Path }); 
groupdirentry.CommitChanges(); 
groupdirentry.Invoke(
    "GetInfoEx", 
    new object[] { 
     new object[] { "primaryGroupToken" }, 
     0 
    } 
); 
object primaryGroupToken = groupdirentry.Invoke(
    "Get", 
    new object[] { "primaryGroupToken" } 
); 
computer.Invoke(
    "Put", 
    new object[] {"primaryGroupID",primaryGroupToken} 
); 
computer.CommitChanges(); 
+0

谢谢托尼,那里有很好的代码。不幸的是,我没有权限将计算机添加到组中。是否有可能在组内创建电脑? 我在广告中遇到以下行为: 当我在计算机中创建'rightclick> new> computer'时。 当我用我的工具创建计算机主体组是“域用户”。当我尝试在AD中更改它后,我收到“访问被拒绝”的错误 –

+0

因此,您在更改主体组时发生错误,或者更改主体组时出现错误,尤其是域计算机? – TonyW

+0

我得到一个错误,更改主域组专门到域计算机,那为什么我要求一种方法来创建已与域计算机主要组的计算机 –

0

您需要设置primaryGroupId到515,我相信(域计算机)

newComputer.Properties["primaryGroupId"].Value = 515 
+0

大卫您好,感谢您的评论,我已经试过了。我收到以下错误消息: “服务器不愿处理请求。” 可能这是一个权限问题?如果是这样,我不明白为什么我可以直接在AD中使用相同的代理帐户创建计算机。 –

相关问题