Friday, 30 January 2015

Reset AD User Password with C#

We can reset Active Directory User password using DirectoryEntry class and UserPrincipal class. In this article, I am going to write C# code snippets to reset AD user password and Reset Bulk AD users password in different methods.

Summary:


Reset AD User Password in C# using UserPrincipal

To use this class, you need to add reference System.DirectoryServices.AccountManagement.dll. The below C# code enable an Active Directory user if it is disabled and reset its password. It also force user to change password at next logon, remove the line user.ExpirePasswordNow(); if you don't want to force user to change password at next logon.
public static void ResetPassword1(string userName, string newPassword)
{
    PrincipalContext context = new PrincipalContext(ContextType.Domain);
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
    //Enable Account if it is disabled
    user.Enabled = true;
    //Reset User Password
    user.SetPassword(newPassword);
    //Force user to change password at next logon
    user.ExpirePasswordNow();
    user.Save();
}

Reset AD User Password in C# using DirectoryEntry

You can also reset Active Directory user password by invoking SetPassword method through DirectoryEntry class, To use this class, you need to add reference System.DirectoryServices.dll.
public static void ResetPassword(string userName, string password)
{
    DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
    DirectorySearcher dirSearcher = new DirectorySearcher(domainEntry);
    string filter = string.Format("(SAMAccountName={0})", userName);
    dirSearcher.Filter = filter;
    SearchResult result = dirSearcher.FindOne();
    if (result != null)
    {
        DirectoryEntry userEntry = result.GetDirectoryEntry();

        //Enable Account if it is disabled
        userEntry.Properties["userAccountControl"].Value = 0x200;
        //Reset User Password
        userEntry.Invoke("SetPassword", new object[] { password });
        //Force user to change password at next logon
        userEntry.Properties["pwdlastset"][0] = 0;
        userEntry.CommitChanges();
        userEntry.Close();
    }
    else
    {
        // User not found
    }
}

Reset Bulk AD Users Password From CSV File

The below C# function read bulk ad user's samAccountName from csv file and reset its password. We are using the Visual basic class TextFieldParser to read CSV file, so we need to add reference dll Microsoft.VisualBasic.

public static void ResetBulkADUsersPasswordFromCSVFile()
{
    string csvFilePath = @"C:\ADUsers.csv";
    string randomPwd = "MyP@ssw0rd";
    using (TextFieldParser csvReader = new TextFieldParser(csvFilePath))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        // reading column fields 
        string[] colFields = csvReader.ReadFields();
        int index_samaccountName = colFields.ToList().IndexOf("samAccountName");
        PrincipalContext context = new PrincipalContext(ContextType.Domain);
        while (!csvReader.EndOfData)
        {                
            try
            {
                // reading user fields 
                string[] fieldData = csvReader.ReadFields();
                string userName = fieldData[index_samaccountName];
                UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
                //Enable Account if it is disabled
                user.Enabled = true;
                //Reset User Password
                user.SetPassword(randomPwd);
                //Force user to change password at next logon
                user.ExpirePasswordNow();
                user.Save();
            }
            catch (Exception ex)
            {
            }
        }
    }
}

Advertisements
Advertisements

No comments:

Post a Comment