How to inform users that their password is about to expire
I got several requests to publish the latest version of a script I wrote once to retrieve all mail enabled user accounts that have the password configured to never expire. Once the accounts are retrieved, based on the DaysToExpire variable value, a mail message is sent to the users stating that their password will expire in X days.
Notice that the script requires the latest version of Quest AD cmdlets and is also compatible with PowerShell version 1 or 2.
$ReqVersion = [version]"1.2.2.1254"
$QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version
if($QadVersion -lt $ReqVersion)
{
throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version"
}
function Send-Mail
{
param($SmtpServer,$From,$To,$Subject,$Body)
$smtp = new-object system.net.mail.smtpClient($SmtpServer)
$mail = new-object System.Net.Mail.MailMessage
$mail.from= $From
$mail.to.add($To)
$mail.subject= $Subject
$mail.body= $Body
$smtp.send($mail)
}
$MaxPassAge = (Get-QADObject (Get-QADRootDSE).defaultNamingContextDN).MaximumPasswordAge.days
if($MaxPassAge -le 0)
{
throw "Domain 'MaximumPasswordAge' password policy is not configured."
}
$DaysToExpire = 14
$MailForm = "you@domain.com"
$PSEmailServer = "exServerName"
Get-QADUser -Enabled -PasswordNeverExpires:$false -SizeLimit 0 -Email * |`
Select-Object Name,Email,@{Name="Expires";Expression={ $MaxPassAge - $_.PasswordAge.days }} |`
Where-Object {$_.Expires -gt 0 -AND $_.Expires -le $DaysToExpire } | Foreach-Object {
$Subject="Password reminder: Your Windows password will expire in $($_.Expires) days"
if($PSVersionTable)
{
# PowerShell Version 2 detected
Send-MailMessage -From $MailForm -To $_.Email -Subject $Subject -Body $Subject
}
else
{
# code for PowerShell v1
Send-Mail -SmtpServer $PSEmailServer -From $MailForm -To $_.Email -Subject $Subject -Body $Subject
}
}