将AD用户添加到AD组

时间:2012-12-24 17:32:58

标签: vb.net active-directory active-directory-group

我有一个VB应用程序(.NET 4.0),用户选择他们拥有的AD组,然后可以将用户从预定义列表添加到该组。这些组从AD中撤出,用户从Oracle中撤出,但都是现有的AD用户。

您将看到三个已注释的代码块,我已经尝试了所有三个代码块并且每个都获得“用户代码未处理的COMException:未指定的错误”。

<WebMethod()> _
Public Shared Function AddDirectReport(ByVal User As String, ByVal Group As String) As String
    Dim GroupMembers As List(Of String) = LoadGroupMembers(Group)
    If GroupMembers.Contains(User) Then
        Return "USER " & User & " IS ALREADY IN GROUP " & Group
    End If

    Dim SearchRoot As New DirectoryEntry("[LDAP Path]")

    Dim GroupSearcher As New DirectorySearcher
    With GroupSearcher
        .SearchRoot = SearchRoot
        .Filter = "(&(ObjectClass=Group)(CN=" & Group & "))"
    End With

    Dim UserSearcher As New DirectorySearcher
    With UserSearcher
        .SearchRoot = SearchRoot
        .Filter = "(&(ObjectClass=Person)(CN=" & User & "))"
    End With

    Dim g As DirectoryEntry = GroupSearcher.FindOne.GetDirectoryEntry
    Dim u As DirectoryEntry = UserSearcher.FindOne.GetDirectoryEntry

    'With u
    '    .Properties("memberof").Add(g)
    '    .CommitChanges()
    'End With

    'With g
    '    .Properties("member").Add(u)
    '    .CommitChanges()
    'End With

    'With g
    '    .Properties("members").Add(u)
    '    .CommitChanges()
    'End With
    Return "Success?"
End Function

1 个答案:

答案 0 :(得分:2)

This是一个很好的资源。

在其中,你会发现你的第二个几乎就在那里。您无需将DirectoryEntry传递给add方法,而是需要其可分辨名称:

With g
    .Properties("member").Add(u.Properties("distinguishedName").Value)
    .CommitChanges()
End With