Friday, 28 March 2014

Restore Deleted AD User in C#


In this article, I am going write C# code to Restore Deleted Active Directory User Account. This Restore process contains following three operations.

Main function to Restore Deleted User in C#

Before proceed, you need to add two dll references System.DirectoryServices and System.DirectoryServices.Protocols.
    static void Main()
        string domainDN = "DC=Work2008,DC=local";
        string domainController = "DevDC";
        string delUser_samAccountName = "del_test";
        SearchResult searchResult = SearchAndGetDeletedObject(domainDN, delUser_samAccountName);

        if (searchResult != null)
            string deletedObjectDN = searchResult.Properties["distinguishedName"][0].ToString();
            string newDN = GetNewDNToRestore(searchResult);
            NetworkCredential netCredential = new NetworkCredential("Administrator", "Password1234", "work2008.local");
            RestoreTombstone(deletedObjectDN, newDN, domainController, netCredential);

Search And Find Deleted AD User by samAccountName in C#

Here, we are searching Deleted AD user by its samAccountName, you can also search it by ObjectGuid or ObjectSID.
private static SearchResult SearchAndGetDeletedObject(string domainDN, string deletedUserName)
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://CN=Deleted Objects," + domainDN, "Administrator", "Password1234");
        dirEntry.AuthenticationType = AuthenticationTypes.FastBind | AuthenticationTypes.Secure;

        DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry, string.Format("(&(isDeleted=TRUE)(sAMAccountName={0}))",

        dirSearcher.CacheResults = false;
        dirSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
        dirSearcher.Tombstone = true;

        SearchResult searchResult = dirSearcher.FindOne();
        return searchResult;

Make new DistinguishedName to Restore Deleted AD User from CN and LastKnownParent

Here, we are making new DistinguishedName to Restore Deleted AD User. We need to move this user to the OU where it was located before delete. We can get Old OU's DN from the attribute lastKnownParent.
private static string GetNewDNToRestore(SearchResult searchResult)
        string newDN = string.Empty;

        string cn = searchResult.Properties["cn"][0].ToString().Split(new char[] { '\n' })[0];

        // Remove special characters 
        cn = cn.Replace(@"\", @"\\");
        cn = cn.Replace(@",", @"\,");

        string lastKnownParent = searchResult.Properties["lastKnownParent"][0].ToString();

        newDN = string.Format("cn={0},{1}", cn, lastKnownParent);

        return newDN;

Restore Deleted Active Directory User from Tombstone in C#

This is the final process to Move Deleted AD user into Old OU where it was located before delete.
private static void RestoreTombstone(string deletedObjectDN, string newDN, string domainControllerName, NetworkCredential credential)
        LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(domainControllerName), credential, AuthType.Negotiate);
        using (connection)
            connection.SessionOptions.ProtocolVersion = 3;

            // to remove value of isDeleted attribute
            DirectoryAttributeModification deleteIsDeletedAttr = new DirectoryAttributeModification();
            deleteIsDeletedAttr.Name = "isDeleted";
            deleteIsDeletedAttr.Operation = DirectoryAttributeOperation.Delete;

            // to remove value of isDeleted attribute
            DirectoryAttributeModification replaceDNAttr = new DirectoryAttributeModification();
            replaceDNAttr.Name = "distinguishedName";
            replaceDNAttr.Operation = DirectoryAttributeOperation.Replace;

            ModifyRequest request = new ModifyRequest(deletedObjectDN, new DirectoryAttributeModification[] { deleteIsDeletedAttr, replaceDNAttr });
            request.Controls.Add(new ShowDeletedControl());

                ModifyResponse response = (ModifyResponse)connection.SendRequest(request);
                if (response.ResultCode == ResultCode.Success)
                    Console.WriteLine("Deleted Active Directory User Restored Successfully.");
                    Console.WriteLine("Failed to Restore Deleted AD User.");
            catch (Exception exception)
                Console.WriteLine("Failed to Restore Deleted AD User:" + exception.Message);

Software Developer


No comments:

Post a Comment