Thursday, October 10, 2013

Get A list of Users with Password expire in 2 days and notify them by Email

My Company policy do not allow any user with "Password Never Expire" except for Services access, All other users (human being) must change their password every 30 days.
So one of the main problem is that there are several users in travel and need to  view their emails using mobile client application which dont have a password expir-ation track, so I write this script that will get a list of users that has been using his password for more than 27 day and report

#I like to clear the screen before starting
#The NeverUser value will hold the Enabled users information only
#this Done by using the userAccountControl attrib, if this attrib is 512 it mean that the account is Enabled
#If This value is 514 this mean that the account is disabled
$NeverUser=Get-ADUser -Properties displayname,sAmAccountName,pwdlastset,mail  -Filter{userAccountControl -eq 512} -SearchBase "OU=Employees,DC=Domain,DC=local" | select displayname,sAmAccountName,pwdlastset,mail

#Now I will start reading the value in the NeverUser
Foreach($SingleUser in $NeverUser){
#$First Date will hold the Last date the user set his password
#SecondDate will hold the value of the current date, you will know why in the next line
$SecondDate= Get-Date
#the calculation I used is to subtract the current date from the date when the user set his password
#the result will be the number of days the user is using the current password
$Result= $SecondDate -$FirstDate
#In my example I will generate a list of users who use their password for a period between 27 and 28 days, you may ask why? 
# First no need to inform a user with an already expired password that his       password will expire soon, as its already expire and he can not login
# Disabled user object may have the pwdLastSet very high (even i exclude them    using the Filter in Get-ADuser)
#This script is made to run everyday, without this restriction, the script will  send the user emails regarding their password till forever come and this is not  needed
if ($Result.Days -gt 26 -and $Result.days -le 29){
$ManyDays =30 - $Result.Days
#The Email Body, you can make it what ever you want
$EmailMessage ="Good day 
Your Password will Exipre in $ManyDays."
#Send-MailMessage used to send an Email message, you can also include attachment if you want  
Send-MailMessage -to $SingleUser.mail -From "" -Subject "Please Change your password" -Body $EmailMessage -SmtpServer "Your.Mail.Server"
} }
Post a Comment