script that sends mail when password expires in X days

#———- Made By: Mark Arnoldus, For PowerShell 3.0 Script —————-

Import-Module ActiveDirectory
Start-Sleep -s 10

function sendMail{

Write-Host “Sending Email”
$EmailSender = “”
$Emailaddress = “”
$Bodytext = “Your text ”

$Subjecttext = “subject”

$smtpServer = “smtp.demo.local”

#Creating a Mail object
$msg = new-object Net.Mail.MailMessage

#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#Email structure
$msg.From = $EmailSender
$msg.ReplyTo = $EmailSender
$msg.subject = $Subjecttext
$msg.body = $Bodytext

#Sending email

#Get All users with password cannot expire
$PasswordCannotExpire = (get-aduser -ldapfilter “(&(&(objectCategory=user)(userAccountControl=66048)))”).samaccountname

#Get All users in AD that are enabled
$AllEnabledUsers = (get-aduser -ldapfilter “(&(&(objectCategory=user)(userAccountControl=512)))”).samaccountname

#For each users
foreach ($EnabledUser in $AllEnabledUsers) {

#Get GivenName
$GivenName = (get-aduser -Identity $EnabledUser).GivenName

# Set parameters
$Expnotificationdays = 5
$IsIttrue = “True”

# Users with Password cannot expire
$IsUserInCannotExpire = $PasswordCannotExpire -contains $EnabledUser

# Max password age
$MaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days

# Password last set
$PasswordLastSet = (get-aduser -identity $EnabledUser -properties *).PasswordLastSet

# Date that password will expire
$ExpiryDate = ($PasswordLastSet).AddDays($MaxPasswordAge)

# Current Date
$CurrentDate = Get-Date

# Difference in expirydate minus the current date
$DifferenceExpiryDateCurrentDate = ($ExpiryDate-$CurrentDate).Days

# If $DifferenceExpiryDateCurrentDate is less or equal to 0 than it is zero.
if ($DifferenceExpiryDateCurrentDate -le 0) {$DifferenceExpiryDateCurrentDate = 0}

# If x days to expire is less or equil to warning tresshold date for expiration and User is not an cannot expire User Then mail the user and give output to command prompt.
if ($DifferenceExpiryDateCurrentDate -le $Expnotificationdays -And $IsUserInCannotExpire -ne $IsItTrue) {$EnabledUser + ” ” + $GivenName +” ” + $DifferenceExpiryDateCurrentDate

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s