Add User to Active Directory In vb.net

Occasionally I need to add a user (or a fake user for test purposes) to active directory. THis is the code I came up with. Hope it helps someone.
 
Public Function AddUser(ByVal domain As String, ByVal loginName As String, ByVal pwd As String, ByVal username As String, ByVal group As String)
            Dim int1, int2 As Integer
            Dim FirstName, LastName, MI As String
            int1 = username.IndexOf(" ")
            int2 = username.LastIndexOf(" ")
            If Not int2 = int1 Then
                FirstName = username.Substring(0, int1)
                MI = username.Substring(int1 + 1, 1)
                LastName = username.Substring(int2 + 1)
            Else
                FirstName = username.Substring(0, int1)
                LastName = username.Substring(int1 + 1)
            End If
            Dim DE As DirectoryEntry = New DirectoryEntry(_path, domain & "\" & loginName, pwd)
            Dim OU As DirectoryEntry = DE.Children.Find("CN=USERS")
            Dim NewUser As DirectoryEntry = OU.Children.Add("CN=" & username, "User")
            NewUser.Properties("sAMAccountName").Value = username
            NewUser.Properties("userPrincipalName").Add(username & "@NLM.LAN")
            NewUser.Properties("GivenName").Add(FirstName)
            If Not MI = Nothing Then
                NewUser.Properties("initials").Add(MI)
            End If
            NewUser.Properties("sn").Add(LastName)
            NewUser.Properties("displayName").Add(username)
            NewUser.Properties("description").Add(group)
            NewUser.CommitChanges()
            NewUser.Invoke("SetPassword", "temp")
            Dim grp As DirectoryEntry = OU.Children.Find("CN=" & group)
            If grp.Name <> "" Then
                grp.Invoke("Add", NewUser.Path.ToString())
            End If

            Dim userACFlags As Object = NewUser.Properties("userAccountControl").Value
            NewUser.Properties("userAccountControl").Value = userACFlags Xor &H2
            NewUser.Properties("PwdLastSet").Value = 0
            NewUser.CommitChanges()
            Console.WriteLine("Account Created Successfully")
        End Function

Advertisements
  1. #1 by Randy Hersom on August 13, 2012 - 1:30 pm

    Don’t forget to right click your app and add a reference to System.DirectoryServices, then put Imports System.DirectoryServices at the top

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: