从AD c中删除计算机帐户#

时间:2014-09-08 03:44:42

标签: c#-4.0 active-directory

我正在尝试使用以下代码从AD中删除计算机帐户:

string ldapBase = "ldap://x.y.z.com/";
string sFromWhere = ldapBase + "rootDSE";
DirectoryEntry root = new DirectoryEntry(sFromWhere, null, null, AuthenticationTypes.Secure);
string defaultNamingContext = root.Properties["defaultNamingContext"][0].ToString();

/* Retrieving the computer to remove */
sFromWhere = ldapBase + defaultNamingContext;
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, null, null, AuthenticationTypes.Secure);

DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase);
dsLookForDomain.Filter = "(&(cn=waprptest))"; // MACHSUPR is the computer to delete
dsLookForDomain.SearchScope = SearchScope.Subtree;
dsLookForDomain.PropertiesToLoad.Add("cn");
dsLookForDomain.PropertiesToLoad.Add("distinguishedName");

SearchResultCollection srcComputer = dsLookForDomain.FindAll();

// Deleting computer 
foreach (SearchResult aComputer in srcComputer)
{
  DirectoryEntry computerToDel = aComputer.GetDirectoryEntry();
  computerToDel.DeleteTree();
  computerToDel.CommitChanges();
}

我得到了异常@

string defaultNamingContext = root.Properties["defaultNamingContext"][0].ToString();

因为rot.Properties计数为0

请让我知道我做错了什么......我是AD的新手

1 个答案:

答案 0 :(得分:1)

根据我的经验,要获取RootDSE文件夹,您必须使用此LDAP字符串:

LDAP://RootDSE

首先,所有大写字母中的LDAP 必须,而RootDSE在其开头也有一个大写R。 LDAP字符串 区分大小写!

此外:如果您使用的是.NET 3.5或更高版本,则可以使用PrincipalSearcher和“按示例查询”主体进行搜索(比使用DirectorySearcher简单得多! ):

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a ComputerPrincipal 
   ComputerPrincipal qbeComputer = new ComputerPrincipal(ctx);

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeComputer);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal"
       ComputerPrincipal cp = found as ComputerPrincipal;

       if (cp != null)
       {
           // do something with the computer account 
       }
   }
}

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。