我正在构建一个退役应用程序,允许个人提供计算机名称,该实用程序将从各个位置清除并清除计算机记录。尝试从Active Directory中删除计算机帐户时遇到问题。我冒充一个只有特定OU结构中“删除所有子对象”权限的服务帐户。如果我使用我的域管理员帐户运行它,则以下代码有效;但是,当我使用模拟的服务帐户运行它时,会因“访问被拒绝”而失败。我已经验证AD中的权限是正确的,因为我可以使用“runas”启动Active Directory用户和计算机并提供服务帐户凭据,我可以完全删除计算机对象。
想知道是否有人之前遇到此问题,或者在使用我当前的OU权限时采用不同的方式对此进行编码。我的直觉告诉我,“DeleteTree”方法正在做更多事情,然后删除对象。
任何帮助将不胜感激。
Sub Main()
Dim strAsset As String = "computer9002"
Dim strADUsername As String = "serviceaccount@domain.com"
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
答案 0 :(得分: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中的用户和群组一起玩!
答案 1 :(得分:0)
删除树与删除不同。您将需要子计算机对象上的“删除子树”权限才能使其生效。