【问题标题】:ASP.NET - Deleting Computer Accounts Within ADASP.NET - 删除 AD 中的计算机帐户
【发布时间】:2012-05-08 08:35:10
【问题描述】:

我正在构建一个停用应用程序,该应用程序将允许个人提供计算机名称,该实用程序将出去并从各个位置清除计算机记录。尝试从 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

【问题讨论】:

    标签: vb.net active-directory


    【解决方案1】:

    如果您使用的是 .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 中与用户和组一起玩变得非常容易!

    【讨论】:

    • 完美。是的,我使用的是 4.0,所以它按预期工作。非常感谢您的帮助。
    【解决方案2】:

    删除树不同于删除。您需要对子计算机对象具有删除子树权限才能使其正常工作。

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 2018-11-02
      • 2017-12-15
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 2021-08-20
      相关资源
      最近更新 更多