Howto: Update user property in Active Directory using Visual Basic .NET (System.DirectoryServices)

To update a user property in your Active Directory (e.g. telephone, common name, description), you can use this function. The DirectoryEntry should point to the specific user that you wish to update.

”’ <summary>
”’ A function that set the property of an object in Active Directory
”’ </summary>
”’ <param name=”DirEntry”>The DirectoryEntry to use eq the user</param>
”’ <param name=”PropertyName”>The property to set</param>
”’ <param name=”PropertyValue”>The value to set to the property</param>
”’ <returns>true/false</returns>
”’ <remarks></remarks>
Private Function AdUserSetProperty(ByVal DirEntry As DirectoryEntry, ByVal PropertyName As String, ByVal PropertyValue As String) As Boolean

    AdUserSetProperty = False

    ‘Specifying Administrator Account
    DirEntry.Username = My.Settings.AdAdminUserName
    DirEntry.Password = My.Settings.AdAdminPassword

    Try
        ‘If the property has a value
        If Not PropertyValue Is Nothing Then

            ‘Does the property exist
            If DirEntry.Properties.Contains(PropertyName) Then

                ‘Setting the new value
                DirEntry.Properties(PropertyName)(0) = PropertyValue

            Else

                ‘Creating the property if it does not exist
                DirEntry.Properties(PropertyName).Add(PropertyValue)

            End If

            ‘Applying the changes
            DirEntry.CommitChanges()
            ‘Closing
            DirEntry.Close()

        End If

        ‘Returning
        AdUserSetProperty = True

    Catch ex As Exception
        ‘Returning
        AdUserSetProperty = False
        ‘Throwing an error
        Throw New Exception(ex.Message, ex.InnerException)
    End Try

End Function

Leave a Comment