Howto: Delete user from Active Directory using Visual Basic .NET (System.DirectoryServices)

Small function to delete a user from Active Directory.

”’ <summary>
”’ A function that deletes a user from Active Directory
”’ </summary>
”’ <param name=”DirEntry”>The Directory Entry that specifies the OU that holds the user</param>
”’ <param name=”sCommonName”>The Common Name (CN) of the user to delete</param>
”’ <returns>true/false</returns>
”’ <remarks></remarks>
Private Function AdUserDelete(ByVal DirEntry As DirectoryEntry, ByVal sCommonName As String) As Boolean

    ‘Returning false if something goes wrong
    AdUserDelete = False

    Try

        ‘Finding the user
        Dim _User As DirectoryEntry = DirEntry.Children.Find(“CN=” & sCommonName, “User”)

        ‘Removing the user
        DirEntry.Children.Remove(_User)

        ‘Committing the changes
        DirEntry.CommitChanges()

        ‘Closing
        DirEntry.Close()

        ‘Went well – returning true
        AdUserDelete = True

    Catch ex As Exception
        ‘Throwing an error
        Throw New Exception(ex.Message, ex.InnerException)
    End Try
End Function

Leave a Comment