繁体   English   中英

在VB.Net中将用户添加到AD组(2008)

[英]Adding User to AD Group in VB.Net (2008)

我需要使用VB将用户添加到Active Directory。 我发现了有效的代码(大多数情况下),除了将用户分配给一个组之外。 我相当确定代码可以正常工作,只是不知道要传递给它的组的格式。

给定代码(如下)和我的AD结构的图像(下),传递给例程以将用户添加到组“ Level1 / All Users / Level 2 / AK”的GroupName的结构是什么?

TIA

Public Shared Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal deUser As DirectoryEntry, ByVal GroupName As String)
Dim deSearch As DirectorySearcher = New DirectorySearcher()
deSearch.SearchRoot = de
deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
Dim results As SearchResultCollection = deSearch.FindAll()
Dim isGroupMember As Boolean = False
If results.Count > 0 Then
    Dim group As New DirectoryEntry(results(0).Path)
    Dim members As Object = group.Invoke("Members", Nothing)
    For Each member As Object In CType(members, IEnumerable)
        Dim x As DirectoryEntry = New DirectoryEntry(member)
        Dim name As String = x.Name
        If name <> deUser.Name Then
            isGroupMember = False
        Else
            isGroupMember = True
            Exit For
        End If
    Next member
    If (Not isGroupMember) Then
        group.Invoke("Add", New Object() {deUser.Path.ToString()})
    End If
    group.Close()
End If
Return

End Sub

在此处输入图片说明

根据您的评论意见,我为您设置了此Sub

您尚未阐明Level2以下的水平,因此我将其称为Level3

此功能已使用户成为禁用用户是无用的...

参考文献:

Imports System.DirectoryServices

如何使用:

CreateUser("Doe", "John")

方法:

Public Sub CreateUser(ByVal givenname As String, ByVal surname As String)

    Dim dom As New DirectoryEntry()
    Dim ou As DirectoryEntry = dom.Children.Find("OU=All Users")
    Dim ou2 As DirectoryEntry = ou.Children.Find("OU=Level2")
    Dim ou3 As DirectoryEntry = ou2.Children.Find("OU=Level3")

    Dim firstLetter As String = givenname.Substring(0, 1)
    Dim ou4 As DirectoryEntry

    If firstLetter Like "*[A-K]*" Then
        ou4 = ou3.Children.Find("OU=A-K")
    Else
        ou4 = ou3.Children.Find("OU=L-Z")
    End If

    Dim ADuser As DirectoryEntry = ou4.Children.Add("CN=" & givenname & "\, " & surname, "user")

    ADuser.CommitChanges()

    'The User is now created. Most people forget to enable their users so I'll put it in here too 

    'UF_DONT_EXPIRE_PASSWD 0x10000
    Dim exp As Integer = CInt(ADuser.Properties("userAccountControl").Value)
    ADuser.Properties("userAccountControl").Value = exp Or &H1
    ADuser.CommitChanges()
    'UF_ACCOUNTDISABLE 0x0002
    Dim val As Integer = CInt(ADuser.Properties("userAccountControl").Value)
    ADuser.Properties("userAccountControl").Value = val And Not &H2
    ADuser.CommitChanges()


End Sub

见我的答案在这个职位与AD和LDAP交互的基本知识。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM