Overview
Imagine it’s Monday morning, it’s 8:00 a.m., the work week isn’t even a full minute old, and the CEO is calling the support line, frantic because his password expired and now he can’t login to give a presentation. Talk about a nightmare way to start the week.
Thankfully this can all be avoided with a simple PowerShell script. Our tip of the week will show you how to notify your employees that their password is going to expire, and avoid this kind of painful support call.
This script is courtesy of Robert Pearman, and you can find the TechNet Gallery article here. Today’s script will be very easy to use. First, you’ll modify the script to match your environment; then we’ll show you how to setup a scheduled task so that the process is automated.
Here are the steps:
- Modify the PowerShell script. Everything in bold will need to be modified to match your environment.
###########################Credit##############################
# Version 1.4 February 2016
# Robert Pearman (WSSMB MVP)
# TitleRequired.com
# Script to Automated Email Reminders when Users Passwords due to Expire.
# Requires: Windows PowerShell Module for Active Directory
# For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content
########################Start of Script###########################
# Please Configure the following variables….
$smtpServer=”mail.server.com“
#When the expirary date is less than the number below, the user will be notified
$expireindays = 21
$from = “Company Administrator <[email protected]>”
$logging = “Enabled” # Set to Disabled to Disable Logging
$logFile = “<log file path>” # ie. “c:mylog.csv”
$testing = “Enabled” # Set to Disabled to Email Users
$testRecipient = “[email protected]“
#############################################################
# Check Logging Settings
if (($logging) -eq “Enabled”)
{
# Test Log File Path
$logfilePath = (Test-Path $logFile)
if (($logFilePath) -ne “True”)
{
# Create CSV File and Headers
New-Item $logfile -ItemType File
Add-Content $logfile “Date,Name,EmailAddress,DaystoExpire,ExpiresOn,Notified”
}
} # End Logging Check
# System Settings
$textEncoding = [System.Text.Encoding]::UTF8
$date = Get-Date -format ddMMyyyy
# End System Settings
# Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired
Import-Module ActiveDirectory
$users = get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq “True”} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
# Process Each User for Password Expiry
foreach ($user in $users)
{
$Name = $user.Name
$emailaddress = $user.emailaddress
$passwordSetDate = $user.PasswordLastSet
$PasswordPol = (Get-AduserResultantPasswordPolicy $user)
$sent = “” # Reset Sent Flag
# Check for Fine Grained Password
if (($PasswordPol) -ne $null)
{
$maxPasswordAge = ($PasswordPol).MaxPasswordAge
}
else
{
# No FGP set to Domain Default
$maxPasswordAge = $DefaultmaxPasswordAge
}
$expireson = $passwordsetdate + $maxPasswordAge
$today = (get-date)
$daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
# Set Greeting based on Number of Days to Expiry.
# Check Number of Days to Expiry
$messageDays = $daystoexpire
if (($messageDays) -gt “1”)
{
$messageDays = “in ” + “$daystoexpire” + ” days.”
}
else
{
$messageDays = “today.”
}
# Email Subject Set Here
$subject=”Your password will expire $messageDays”
# Email Body Set Here, Note You can use HTML, including Images.
$body =”
Dear $name,
<p> Your Password will expire $messageDays<br>
To change your password on a PC press CTRL ALT Delete and chose Change Password <br>
<p>Thanks, <br>
</P>”
# If Testing Is Enabled – Email Administrator
if (($testing) -eq “Enabled”)
{
$emailaddress = $testRecipient
} # End Testing
# If a user has no email address listed
if (($emailaddress) -eq $null)
{
$emailaddress = $testRecipient
}# End No Valid Email
# Send Email Message
if (($daystoexpire -ge “0”) -and ($daystoexpire -lt $expireindays))
{
$sent = “Yes”
# If Logging is Enabled Log Details
if (($logging) -eq “Enabled”)
{
Add-Content $logfile “$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent”
}
# Send Email Message
Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding
} # End Send Message
else # Log Non Expiring Password
{
$sent = “No”
# If Logging is Enabled Log Details
if (($logging) -eq “Enabled”)
{
Add-Content $logfile “$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent”
}
}
} # End User Processing
##########################End of script##########################
2. Save the script to the location of your choosing.
3. Open Task Manager and select ‘Create New Task’. Give it a proper name and ensure that ‘Run whether user is logged on or not’ is selected and that ‘Run with highest privileges’ is selected. Sensitive information has been removed from this graphic.
4. Define the Triggers tab. Configure the task for ‘Daily’ and ‘Enabled’
5. Next select the Actions tab. Browse to the location of the script and then append the following to the ‘Program/script:’ section: exe –file
The entire string will look like this:
powershell.exe -file C:supportscriptspassword_expiry_email.ps1
6. The rest of the settings can stay at the default settings.
7. Click OK and enter the username and password of the user account. *Note the user account will require ‘run scheduled task/batch file permissions’. Sensitive information removed from the screenshot.
8. Click yes at the next prompt.
Tip – Just in case the users don’t change their password after the first reminder, we recommend that you set up a second schedule task to remind your users again, three days before their password expires. For the additional reminder, modify the $expireindays variable from 21 to 4. There’s always a chance you have a procrastinator in your midst, and this way you’ll help to keep them from making that frantic call right before their big presentation.
This script is configured for ‘Test Mode’ by default. Test mode sends an email to the administrator, instead of to each user. To take the script out of test mode, simply change the $testing variable from Enabled to Disabled, per the script instructions.
That’s all there is to it. You now have an automated process to notify users to update their password before it’s set to expire. You can see previous tip of the week articles by visiting these links: