Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out an ADUser's password expiry date or days left until password expiry?

I have a list of ADUsers and I want to check if any of the users' passwords are expiring soon, but I can't find any property to check.

like image 463
Muhammad Raja Avatar asked Mar 19 '12 11:03

Muhammad Raja


1 Answers

This should do the trick to find out the time remaining until the password expires for each user:

private static TimeSpan GetTimeRemainingUntilPasswordExpiration(string domain, string userName)
{
    using (var userEntry = new System.DirectoryServices.DirectoryEntry(string.Format("WinNT://{0}/{1},user", domain, userName)))
    {
        var maxPasswordAge = (int)userEntry.Properties.Cast<System.DirectoryServices.PropertyValueCollection>().First(p => p.PropertyName == "MaxPasswordAge").Value;
        var passwordAge = (int)userEntry.Properties.Cast<System.DirectoryServices.PropertyValueCollection>().First(p => p.PropertyName == "PasswordAge").Value;
        return TimeSpan.FromSeconds(maxPasswordAge) - TimeSpan.FromSeconds(passwordAge);
    }
}

Note: you will need to add a reference to System.DirectoryServices.

like image 152
Rob Levine Avatar answered Nov 10 '22 17:11

Rob Levine