如何使用c#从Active Directory中删除计算机帐户

是否有任何样本使用C#从AD中删除计算机帐户?

我搜索了很多来源,但都是关于用户帐户的。

在这里添加了我的代码,我总是出于某种原因出错。

public static bool checkExistingPC(string compName,string userName,string userPwd ) { try { DirectoryEntry entry = new DirectoryEntry("LDAP://test.com",userName,userPwd,AuthenticationTypes.Secure); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + compName + ")(dn=" + compName + ")))"; foreach (SearchResult result in mySearcher.FindAll()) { if (result != null) { MessageBox.Show("computer GetDirectoryEntry():" + result.Path+"\n"+"computer path: "+result.Path); DirectoryEntry entryToRemove = new DirectoryEntry(result.Path,userName,userPwd); entry.Children.Remove(entryToRemove); return true; } else { return false; } } } catch (Exception e) { MessageBox.Show(e.Message); } return false; } 

使用System.DirectoryServices下的ADSI使用提交机制,这是一个工作示例:

 /* Retreiving RootDSE infos */ string ldapBase = "LDAP://WM2008R2ENT:389/"; string sFromWhere = ldapBase + "rootDSE"; DirectoryEntry root = new DirectoryEntry(sFromWhere, "dom\\jpb", "PWD"); string defaultNamingContext = root.Properties["defaultNamingContext"][0].ToString(); /* Retreiving the computer to remove */ sFromWhere = ldapBase + defaultNamingContext; DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", ".biènèsph^r^.1966"); DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase); dsLookForDomain.Filter = "(&(cn=MACHSUPR))"; // MACHSUPR is the computer to delete dsLookForDomain.SearchScope = SearchScope.Subtree; dsLookForDomain.PropertiesToLoad.Add("cn"); dsLookForDomain.PropertiesToLoad.Add("distinguishedName"); SearchResultCollection srcComputer = dsLookForDomain.FindAll(); foreach (SearchResult aComputer in srcComputer) { /* For each computer */ DirectoryEntry computerToDel = aComputer.GetDirectoryEntry(); computerToDel.DeleteTree(); computerToDel.CommitChanges(); } 

如果您使用的是.NET 3.5及更高版本(如果您没有 – 升级时间!),则应查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 在这里阅读所有相关内容:

  • 管理.NET Framework 3.5中的目录安全性主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

基本上,您可以定义域上下文并在AD中轻松查找用户和/或组:

 // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find the computer in question ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, "NAME"); // if found - delete it if (computer != null) { computer.Delete(); } 

新的S.DS.AM让您可以轻松地与AD中的用户,计算机和群组一起玩游戏!

它可能不是您正在寻找的,但此站点提供了许多用于在C#中使用AD的代码示例,包括删除安全组和从组中删除用户

使用WMI和/或System.DirectoryServices命名空间(http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx)。