Unexpected user account expirations can disrupt work and burden IT teams with last-minute access requests. To avoid such situations, you can use PowerShell to send Active Directory account expiration email notification to specified admins. This proactive approach enables admins to either extend the account’s validity or allow it to expire and disable it accordingly.
Use the PowerShell script below to notify admins 10 days before user accounts expire by sending a predefined email notification.
You can replace the value of ‘$ExpiringDays’ with a different threshold based on your requirements.
$ExpiringDays = 10
$Today = Get-Date
$ExpirationDate = $Today.AddDays($ExpiringDays)
$Credential= Get-Credential
$ExpiringUsers = Get-ADUser -Filter
{
accountExpires -lt $ExpirationDate -and accountExpires -gt $Today -and Enabled -eq $true
} -Properties accountExpires, Enabled, Name
foreach ($user in $ExpiringUsers)
{
$FormattedExpiryDate =[datetime]::FromFileTime($user.accountExpires).ToShortDateString()
$UserName= $user.Name
$subject = "Upcoming account expiration alert for $UserName"
$body = @"
Hello Admin,<br>
This is a reminder that the Active Directory account of $UserName is scheduled to expire on $FormattedExpiryDate.
<br>
Please take the necessary action if this account needs to be extended or deactivated.
<br>
Thank you."@
Send-MailMessage -To "<AdminEmailAddress>" -From "<NotificationEmailAddress>" -Subject $subject -Body $body -BodyAsHtml -SmtpServer "<SMTPAddress>" -Port 587 -UseSsl -Credential $Credential
}
Note: The ‘Send-MailMessage’ is considered obsolete as it doesn't support modern authentication or robust security standards. As a secure and up-to-date alternative, you can use the MailKit library , which offers better support for encryption, authentication, and modern protocols.
You can use Task Scheduler to run the script based on your desired frequency. However, it introduces challenges like script failures and credential issues, which may result in missed notifications and delays in operations.
Get Real Time Alerts for Expiring AD User Accounts to Prevent Unexpected Lockouts!
With AdminDroid, you can easily create alerts for expiring Active Directory users and send notifications directly to the desired recipients without configuring SMTP.
You can use ‘Alerts Overview Dashboard’ in the AdminDroid portal to visualize and analyze all the account expiration alerts in Active Directory.