I am developing a simple tool for create local user accounts on windows and add them to administrator group or guest group.
I just need to know that how to enable the "User Must Change The Password At Next Logon" option when creating a new local user account. I am using c# , windows form application to write my script. I have used below code to create the user account and set password to Pass@123 and need to enable "User Must Change The Password At Next Logon" option.
I have tried to use NewUser.Properties["pwdLastSet"].Value = 0;
but this did not worked, threw an exception since this is used for ActiveDirectory.
Can someone assist me regarding this?
try
{
DirectoryEntry AD = new DirectoryEntry("WinNT://"
Environment.MachineName ",computer");
DirectoryEntry NewUser = AD.Children.Add(UserID, "user");
NewUser.Invoke("SetPassword", new object[] { "Pass@123" });
NewUser.Invoke("Put", new object[] { "Description", "A user account managed by system"});
NewUser.Invoke("Put", new object[] { "FullName", "Work From Home: " UserID });
NewUser.CommitChanges();
DirectoryEntry grp;
grp = AD.Children.Find(AccountType, "group");
if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
MessageBox.Show("Account Created Successfully","Successfull", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
CodePudding user response:
I have found how to enable User Must Change Password At Next Logon in a local user account with c# script
NewUser.Properties["PasswordExpired"].Value = 1;
This one worked successfully.
Thank You so much !
CodePudding user response:
Been a while since i had to try to manage a local AD directly from .net code so this might be outdated.
Try: NewUser.Properties["pwdLastSet"][0] = 0;
If I'm not mistaken ["pwdLastSet"] is in itself and ICollection :).
Otherwise i would recommend you look into System.DirectoryServices.AccountManagement. Then you could simply use UserPrincipal.Current.ExpirePasswordNow();
Or something equivalent once you have defined your PrincipalContext. Here is the documentation https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement?view=dotnet-plat-ext-7.0 `