$ADResults = Get-ADUser -SearchBase "DC=domain,DC=name" -Filter {(Enabled -eq $True) -and (EmailAddress -like "*")} -Properties EmailAddress, PasswordExpired, PasswordNeverExpires, PasswordLastSet
$smtpServer = "YourSMTPserver"
$smtpFrom = "Support<[email protected]>"
# LOOP THROUGH USERS IN ACTIVE DIRECTORY
foreach ($user in $ADResults){
$name = $user.Name
$passwordlastset = $user.PasswordLastSet
$passwordexpired = $user.PasswordExpired
$passwordneverexpires = $user.PasswordNeverExpires
$useremail = $user.EmailAddress
# CALCULATE TIME BEFORE PASSWORD EXPIRATION
#if your password has not expired and your password is not set to never expire and your password is not new
if (($passwordexpired -ne $True) -and ($passwordneverexpires -ne $True) -and ($passwordlastset -ne $null)){
$user_enddate = $passwordlastset + ((Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.TotalDays)
$DaysLeft = (New-TimeSpan -Start (Get-Date) -End $user_enddate).Days
# NOTIFY USER IF PASSWORD IS EXPIRING WITHIN 2 WEEKS
if ($DaysLeft -le "9"){
#### Header details to make the email nicer
$Header = "<style>"
$Header = $Header + "BODY{background-color:white;}"
$Header = $Header + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$Header = $Header + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:#CB5DB3}"
$Header = $Header + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:lightgrey}"
$Header = $Header + "</style>"
#### Body
$b = "
<font face='calibri' size='3'>
Dear $name <br>
Your password is due to expire in $DaysLeft day(s)!<br>
If you do not change your password before it expires, you will be unable to access your email and/or computer.<br><br>
<strong>Ways you can change your password.</strong><br>
On your work desktop/laptop - press ctrl/alt del (if you're a remote worker ensure the vpn is connected first) <br>
The webmail portal. <a title='Webmail Portal' href='https://portal.office.com/account/'>Link</a> - Follow the link to Security & Privacy and there will be a link there to change it. <em>(Note - The Safari browser does not support this)</em><br><br>
<strong>Dont forget to also update any devices (mobiles etc) that you use to access your emails.</strong><br><br>
If you need futher assistance you can contact IT support via<br>
01234 123456<br>
Email - <a href='mailto:[email protected]'>[email protected]</a><br><br>
Thank you<br>
Support<br><br>
</font>
<em>This e-mail was automatically generated</em>
"
$body = ConvertTo-HTML -head $a -body $b
$smtpTo = "$useremail"
$messageSubject = "Your password is due to expire in $DaysLeft days"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.Body = $body
If ($DaysLeft -lt 3) {
$message.Priority = "High"
}
$message.IsBodyHTML = $true
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)
}
}
}