Check-PasswordExpiration

Because ‘Password never expires’ is a really bad option for an administrator…

For those who use their Active Directory account (the administrative one…) to connect to remote server roles through an MMC, this script can be very useful. Indeed, it allows you to be notified by email one week before the expiration of the password (by default, configurable).
Because if you do not connect directly to any server, you will never have the information about the expiration of your password, only a message stating that your account is restricted, but whitout telling you why.
Has to be scheduled, every 7 days for example. (if you do not change the ‘$ExpireInDays’ variable value)
http://www.zerrouki.com/schedule-a-powershell-script-execution/

$SmtpServer="mailserver.domain.com"
$ExpireInDays=7
$From="Support Admins <admins@monitor.domain.com>"
$OU="ou=learning,dc=domain,dc=com"

Import-Module ActiveDirectory
$Users=Get-ADUser -Filter * -SearchBase $OU -Properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet | Where {$_.Enabled -eq $True} | Where { $_.PasswordNeverExpires -eq $False } | Where { $_.PasswordExpired -eq $False }

foreach ($User in $Users)
{
$Name=$User.Name
$EmailAddress=$User.UserPrincipalName
$AccountName=$User.SamAccountName
$PasswordSetDate=$User.PasswordLastSet
$PasswordPol=(Get-AduserResultantPasswordPolicy $user)
if ($PasswordPol) { $MaxPasswordAge=($PasswordPol).MaxPasswordAge } else { $MaxPasswordAge=(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge }

$ExpiresOn=$PasswordSetDate + $MaxPasswordAge
$DaysToExpire=(New-TimeSpan -Start (Get-Date) -End $Expireson).Days
$Subject="Your password will expire soon"
$Body=@"
<html><span style='font-family: Tahoma; font-size: 12px;' >$Name,<br />
<br />
your account's ('$AccountName') password will expire in $DaysToExpire days.<br />
Please consider to change it.<br />
<br />
----------------------------------------------------------------------------</span><br />
<span style='font-family: Tahoma; font-size: 10px;' >This email was generated automatically. The sender address is used only for monitoring purposes and is not checked for incoming emails.<br />
Do NOT reply to this email.<br />&nbsp;<br /></span></html>
</p>
"@

if ($DaysToExpire -lt $ExpireInDays) { Send-MailMessage -SmtpServer $SmtpServer -From $From -to $EmailAddress -Subject $Subject -Body $Body -BodyAsHTML -Priority High }
} #EndOf foreach ($user in $users)

Based on/Copied from RobertPearman script

Leave a Reply

Scroll to Top