gaurav kumar
gaurav kumar

Reputation: 1

Need to compare pwdLastSet in Active Directory with current date and check if the password is about to expire. What would be the best way to do that?

I have a requirement to compare pwdLastSet field from Active Directory with current date and if that date difference is a configurable number(fixed by client), we need to trigger email that password is about to expire. This date comparison also needs to be done with LastLoginTimeStamp in Active Directory to send emails. What would be the best way out to compare these fields as pwdLastSet is a long int and using it the DirectorySearcher filter to compare with current date will not be possible.

Upvotes: -1

Views: 2381

Answers (3)

almaceleste
almaceleste

Reputation: 467

You can get the last password set date of a directory user in DateTime type by using nullable LastPasswordSet property of the UserPrincipal class from the System.DirectoryServices.AccountManagement namespace.

If User must change password at next logon option is checked then LastPasswordSet property returns null value. Otherwise it returns the last date and time the password was set in type DateTime. Then you can compare dates with DateTime.Compare mathod.

using(PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Username);
    //? - to mark DateTime type as nullable
    DateTime? pwdLastSet = (DateTime?)user.LastPasswordSet;
    int delta = 7;
    if (pwdLastSet != null)
    {
        if (DateTime.Compare((DateTime)pwdLastSet, DateTime.Now) < delta)
        {
            //send email
            ...
        }
    }
}

MSDN: UserPrincipal
MSDN: LastPasswordSet

Upvotes: 1

DisplayName
DisplayName

Reputation: 1026

To see when pawword is going to expire

Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties “DisplayName”, “msDS-UserPasswordExpiryTimeComputed” |
    Select-Object -Property “Displayname”,@{Name=“ExpiryDate”;Expression={[datetime]::FromFileTime($_.“msDS-UserPasswordExpiryTimeComputed”)}} | export-csv -path c:\paswsword-expiring.csv

See when password was last set

Get-ADUser -filter * -properties Displayname,PasswordLastSet | select displayname,passwordlastset |Format-List

set up email alert

http://www.powershelladmin.com/wiki/Active_directory_password_expiration_notification

Upvotes: 0

user2316116
user2316116

Reputation: 6814

To get a datetime from pwdLastSet:

SearchResult sr = ds.FindOne(); 
hacked = DateTime.FromFileTime((long)sr.Properties["pwdLastSet"][0]); 

See Casting ActiveDirectory pwdLastSet property without using ActiveDs and checking timespan

Upvotes: 0

Related Questions