PowerShell script to email users if password expires soon, and send a summary to IT

I wanted to expand on my previous script: powershell-to-list-all-users-and-when-their-password-expires, so that it would send the user an email if their password was going to expire soon. Additionally I wanted to send a summary to our IT staff of accounts that were going to expire soon.

Here is that script:

$maxdays=(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.TotalDays
$summarybody="Name `t ExpireDate `t DaysToExpire `n"

(Get-ADUser -filter {(Description -notlike "IfYouWantToExclude*") -and (Enabled -eq "True") -and (PasswordNeverExpires -eq "False")} -properties *) | Sort-Object pwdLastSet |
foreach-object {

$lastset=Get-Date([System.DateTime]::FromFileTimeUtc($_.pwdLastSet))
$expires=$lastset.AddDays($maxdays).ToShortDateString()
$daystoexpire=[math]::round((New-TimeSpan -Start $(Get-Date) -End $expires).TotalDays)
$samname=$_.samaccountname
$firstname=$_.GivenName
if ($daystoexpire -le 3){
	$ThereAreExpiring=$true

	$emailFrom = "from@yourdomain.com"
	$emailTo = "$samname@yourdomain.com"
	$subject = "$firstname, your password expires in $daystoexpire day(s)"
	$body = "$firstname,
	Your password expires in $daystoexpire day(s).

	Please press Ctrl + Alt + Del -> Change password"

	$smtpServer = "smtp.yourdomain.com"
	$smtp = new-object Net.Mail.SmtpClient($smtpServer)
	$smtp.Send($emailFrom, $emailTo, $subject, $body)

	$summarybody += "$samname `t $expires `t $daystoexpire `n"
}
}
if ($ThereAreExpiring) {
$emailFrom = "from@yourdomain.com"
$emailTo = "ITSTAFF@yourdomain.com"
$subject = "Expiring passwords"
$body = $summarybody
$smtpServer = "smtp.yourdomain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
}

3 Responses to PowerShell script to email users if password expires soon, and send a summary to IT

  1. KDaniel April 1, 2013 at 12:41 pm #

    Just what i am looking for. Thanks.

  2. Lynsie November 21, 2014 at 11:59 am #

    Hi Jeff, Thank you for all of your scripts. They have saved me a great amount of time and effort. I had a quick question on the password expire script. The output shows LastChanged date as 1/1/1601 and expire 2/12/1601. Is there something I need to change on this script for it to reflect the current year. Thanks for all your help. L

  3. ryanweldron March 30, 2015 at 7:46 am #

    Thanks for sharing this useful script,
    I have an also something to share related to this topic i.e. http://password-expiration-notification.blogspot.in/

Powered by WordPress. Designed by WooThemes