Expiring password reminder email via PowerShell

Enabling tougher password requirements usually results in massive IT headache. Users (especially mobile and remote users) don’t really get much warning as to when their password is going to expire. It’s no fun when users with no direct access to the domain controller let their password expire. The simplest solution is to spam them with more warnings.

While I think this should be built-in Windows functionality, it’s not. There’s even a paid product to fill this hole. Thankfully, lots of people have implemented this via Perl, VB Script and PowerShell. I wanted something as simple as possible, written in PowerShell, so I combined a few sources to make the following. Thanks to Rpieniazek and mjolinor, Steve Blossom and Microsoft


if ((get-module | where { $_.Name -eq "ActiveDirectory"}) -eq $null) { 
        import-module ActiveDirectory; 
        if ((get-module | where { $_.Name -eq "ActiveDirectory"}) -eq $null) {throw "ActiveDirectory Module is required."} 
        } 


$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
	
Get-ADUser -filter * -properties PasswordLastSet, PasswordExpired, PasswordNeverExpires, EmailAddress, GivenName |foreach {
     
	$today=get-date
	$UserName=$_.GivenName

	if (!$_.PasswordExpired -and !$_.PasswordNeverExpires) {

		$ExpiryDate=$_.PasswordLastSet + $maxPasswordAgeTimeSpan
		$DaysLeft=($ExpiryDate-$today).days 
 
		if ($DaysLeft -lt 30 -and $DaysLeft -gt 0){

		$WarnMsg = " 
Hi $UserName

Your password expires in $DaysLeft days, go change it plz. KTHXBAI.

-Team SysAdm

"

send-mailmessage -to $_.EmailAddress -from it@contoso.com -Subject "IT Reminder: Your password will expire in $DaysLeft days" -body $WarnMsg  -smtpserver mailsrv1.contoso.local

		}

	}		
}