2012-04-27 52 views
1

我正在构建一个退役应用程序,该应用程序允许个人提供计算机名称,实用程序将消失并从各个位置清除计算机记录。尝试从Active Directory中删除计算机帐户时遇到问题。我扮演的服务帐户只具有在特定OU结构中“删除所有子对象”的权限。如果我使用我的域管理员帐户运行它,下面的代码工作;但是,当我使用模拟的服务帐户运行它时,会出现“拒绝访问”失败的情况。我已经验证AD中的权限是正确的,因为我可以使用“runas”启动Active Directory用户和计算机并提供服务帐户凭据,并且我可以完美地删除计算机对象。ASP.NET - 删除AD内的计算机帐户

想知道是否有人遇到过这种情况,或者有不同的方式来编码,同时仍然利用我当前的OU权限。我的直觉告诉我,“DeleteTree”方法做得更多,然后只是删除对象。

任何援助将不胜感激。

Sub Main() 
    Dim strAsset As String = "computer9002" 
    Dim strADUsername As String = "[email protected]" 
    Dim strADPassword As String = "password" 
    Dim strADDomainController As String = "domaincontroller.domain.com" 

    Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry 
    Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry) 
    Dim Result As System.DirectoryServices.SearchResult 
    Dim strLDAPPath As String = "" 

    Try 
     objDirectoryEntry.Path = "LDAP://" & strADDomainController 

     objDirectoryEntry.Username = strADUsername 
     objDirectoryEntry.Password = strADPassword 

     objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree 
     objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))" 

     Dim intRecords As Integer = 0 

     For Each Result In objDirectorySearcher.FindAll 
      Console.WriteLine(Result.Path) 
      Diagnostics.Debug.WriteLine("DN: " & Result.Path) 
      Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry() 
      objComputer.DeleteTree() 
      objComputer.CommitChanges() 
      intRecords += 1 
     Next 

     If intRecords = 0 Then 
      Console.WriteLine("No Hosts Found") 
     End If 

    Catch e As System.Exception 
     Console.WriteLine("RESULT: " & e.Message) 
    End Try 
End Sub 

回答

2

如果你在.NET 3.5及以上,你应该看看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读全部内容:

基本上,你可以定义域范围内,并可以轻松地查找用户和/或组AD:

' set up domain context 
Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword) 

' find a computer 
Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset) 

If computerToDelete IsNot Nothing Then 
    ' delete the computer, if found 
    computerToDelete.Delete() 
End If 

的新的S.DS.AM可以很容易地与AD中的用户和群组玩耍!

+0

完美。是的,我使用4.0以便按预期工作。非常感谢你的帮助。 – 2012-04-27 18:22:56

0

删除树不同于删除。您需要在子计算机对象上使用删除子树权限才能使其工作。

+0

有道理。谢谢 – 2012-04-27 18:23:37