I have a List of ADUsers but foreach ADUSER I want to get its property "LastPasswordSet" Which is only accessible (am not sure if there is any other way as well) through UserPrincipal.
If i Use this code,
PrincipalContext l_objContext = new PrincipalContext(ContextType.Domain, l_strDomain, l_strUserOU);
foreach (ADUser ADuser in Users)
{
UserPrincipal usr = UserPrincipal.FindByIdentity(l_objContext, ADuser.CommonName.ToString());
if (usr.LastPasswordSet.HasValue)
{
EmailString(usr.LastPasswordSet.ToString());
}
}
Now I dont want to provide Any thing to UserPrincipal other then Any of property of ADUSER, and the above code doesn't work either, the problem is that its send few emails and then come across somewhere it gives and an error and service stops, which probably because of some unvalid date (I dont want to fix it, just stated so that you get idea of what i am doing)
You can create your own PrincipalContext
and then use UserPrincipal.FindByIdentity
to get the principal. From here, as I suspect you already know, you can call the LastPasswordSet
property.
public static DateTime? GetLastPasswordSet(string domain, string userName)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
return userPrincipal.LastPasswordSet;
}
}
Note: you will need to add a reference to System.DirectoryServices.AccountManagement
[EDIT: in response to further question in comment]
To test if the password was last set over a month ago - something like this:
if (lastPasswordSet < DateTime.Now.AddMonths(-1))
{
// Password last set over a month ago.
}
One thing to bear in mind is that a month is an ambiguous length of time - its length depends on what month (and year) you are in. Depending on what you are trying to do, it may be more suitable to have a fixed period such as 28 days.