Emailing Users when Password is about to Expire

I had one request from a customer recently that asked if it was possible to email users before the their active directory passwords expire as it was causing issues with remote users.

I created a PowerShell script which I added as a scheduled task on one domain controller that runs once  a day. The script queries AD for the date the user last changed their password and compared it against AD password policy maximum age limit. If this reached a specified time such as 5 days before, the user would be emailed once per day with 5 days to go. Please note that you will need an exchange server or mail server that will allow unauthenticated email to be sent from the DC you home this script on.
$smtpServer=”exchangecasserver.domain.local”
$from = “passwordreminder@domain.local”
$expireindays = 5
#Get Users From AD who are enabled
Import-Module ActiveDirectory
$users = get-aduser -filter * -properties * |where {$_.Enabled -eq “True”} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }

foreach ($user in $users)
{
$Name = (Get-ADUser $user | foreach { $_.Name})
$emailaddress = $user.emailaddress
$passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
$expireson = $passwordsetdate + $maxPasswordAge
$today = (get-date)
$daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
$subject=”Your password will expire in $daystoExpire days”
$body =”
Dear $name,
<p> Your Password will expire in $daystoexpire days.<br>
To change your password, Logon to the domain Internal Network on a PC / Laptop, press CTRL ALT Delete and chose Change Password <br>
<p>Thanks, <br>
</P>”

if ($daystoexpire -lt $expireindays)
{
Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s