Inform Active Directory Users of Password Expiration

Sometimes your Active Directory users will appreciate receiving notifications of when their passwords are about to expire. Having your CEO call you on your day off to let you know that they can’t login because their password has expired is never fun.

Creative Commons [by-nc-nd]

Here is a simple Powershell script that you can use to easily send out emails to users with impending password expiration.

All you will need to modify is the “-From” address and the “-SmtpServer” address on line 13 to suit your environment, and potentially the “5” on line 28 to adjust the number of days until expiry that will trigger the email to be sent.

Import-Module ActiveDirectory

function Get-PasswordExpirationDays ($User)
{
    (([datetime]::FromFileTime((Get-ADUser –Identity $User -Properties "msDS-UserPasswordExpiryTimeComputed")."msDS-UserPasswordExpiryTimeComputed"))-(Get-Date)).Days
}

function Send-ExpirationEmail ($expDays,$expEmail,$expFirst,$expLast)
{
    if ([int]$expDays -eq 1) { $expNoun = "day" } else { $expNoun = "days" }
    $expSubject = "Your computer password will expire in $expDays $expNoun"
    $expBody = "Our records indicate that your computer password is due to expire in $expDays $expNoun`r`n"
    Send-MailMessage -From [email protected] -To $expEmail -Subject $expSubject -SmtpServer "smtp.example.com" -Body $expBody
}

$Users = Get-AdUser -filter { passwordNeverExpires -eq $false -and enabled -eq $true }

ForEach ($User in $Users)
{

    $CurrentUser = "" + $User.SamAccountName + ""
    $CurrentEmail = "" + $User.UserPrincipalName + ""
    $CurrentFirst = "" + $User.GivenName + ""
    $CurrentLast = "" + $User.Surname + ""
    
    if ($CurrentEmail -ne "") {
        $CurrentExpiration = Get-PasswordExpirationDays $CurrentUser
        if ([int]$CurrentExpiration -ge 0 -and [int]$CurrentExpiration -le 5 -and $CurrentEmail -notlike "*local*") {
            Write-Host "$CurrentExpiration - $CurrentEmail"
            Send-ExpirationEmail $CurrentExpiration $CurrentEmail $CurrentFirst $CurrentLast
        }
    }

}

Run the script via Task Scheduler once a day, and you’re all set.

However, any decision you might make towards implementing such a mechanism needs to be considered as part of your broader security policy. It may not be appropriate for your organisation, and I make no warranties towards your use of the above code.

Nevertheless, this is a quick and easy way to achieve the goal, if it is right for you.