2012-04-27 54 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