Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Active Directory User Account Password Expiry Email Notification using PowerShell

While working and setting up a new project from scratch, the Helpdesk team wanted a solution to automatically send alert notification to Users about their Accounts password expiring. The notification email format looks like below once password is near defined days in the PowerShell Script. This PowerShell script requires a prerequisite ActiveDirectory module to be installed on the system (You can install RSAT tools or Add Roles and Features) where you can schedule it in the Task Scheduler.

VMware vSphere vCenter ESXi PowerShell Active Directory auditor report expired password notification adReport tool automation microsoft windows domain controller dns.jpg

To use this script there are five parameters you need to provide.

-DaysAfterPasswordExpire: Provide a number value here, The policy after the days user password will expire after days. In my case in my new project User Account password Policy is to set a password that will expire after every 45 days.

-DaysBeforeAlert: Before how many days you need to send notification. Example:2 weeks or one week

-SearchBase: Do you want to send Email notifications to specific Organization unit? Mention the distinguished name (DN) of either domain or OU. Example format 'DC=vcloud-lab,DC=com'

-SMTPServer: Provider (Exchange Email server) SMTP server IP or FQDN here.

-SMTPPort: This parameter asks for a SMTP port. In my case it is 587 (SMTP submission) port number.

Download this script Send-PasswordExpiryNotification.ps1 here or it is also available on github.com/janviudapi.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
##############################
#.SYNOPSIS
#Send email to Users whose password will expired in given days.
#
#.DESCRIPTION
#This script connect and fetches users list whose password is going to expired in the after mentioned days. 
#
#.PARAMETER DaysAfterPasswordExpire
#Provide a value for a configured policy after how many days password will expire.
#
#.PARAMETER DaysBeforeAlert
#This is a parameter to set days alerts before user password should get email notification, Provide a number value.
#
#.PARAMETER SearchBase
#Provide distingushed name for domain/out to search users.
#
#.PARAMETER SMTPServer
#Email server FQDN or IP.
#
#.PARAMETER SMTPPort
#Email server SMTP port for submission dfault value is 587.
#
#.EXAMPLE
#Send-PasswordExpiryNotification -DaysBeforeAlert 30 -SearchBase 'DC=vcloud-lab,DC=com' -From 'no-reply@vcloud-lab.com' -SMTPServer 'emailexchange.vcloud-lab.com' -SMTPPort 587
#
#Finds users with expiring password in Active Directory and send notification email.
#
#.NOTES
#http://vcloud-lab.com
#Written using powershell version 5
#Script code version 1.0
###############################

[CmdletBinding()]
param(
    [Parameter(Position=0)]
    [Int]$DaysAfterPasswordExpire = 45,
    [Parameter(Position=1)]
    [Int]$DaysBeforeAlert = 15,
    [Parameter(Position=2)]
    [System.String]$SearchBase = 'DC=vcloud-lab,DC=com',
    [Parameter(Position=3)]
    [System.String]$From = 'no-reply@vcloud-lab.com',
    [Parameter(Position=4)]
    [System.String]$SMTPServer = 'emailexchange.vcloud-lab.com',
    [Parameter(Position=5)]
    [Int]$SMTPPort = 587
)
Begin {
    if (-not(Get-Module ActiveDirectory)) {
        Import-Module -Name ActiveDirectory
    }
}
Process {
    #$DaysBeforeAlert = 1
    #$searchBase = "DC=vcloud-lab,DC=com"
    #$from = "noreply@vcloud-lab.com"
    #$smtpServer = "192.168.34.42"
    #$smtpPort = "587"
    #$backDate = (Get-Date).AddDays($days)

    $alertDays = $DaysAfterPasswordExpire - $DaysBeforeAlert

    $dateNow = [datetime]::Now
    $expiryDate = $dateNow.AddDays(-$alertDays) #.ToFileTime()

    $filter = {(Enabled -eq $True) -and (PasswordNeverExpires -eq $False) -and (PasswordLastSet -gt $expiryDate)} #-and (PasswordLastSet -gt $rawBackDate)} #-and (PasswordLastSet -gt $backDate) #name -eq 'user1' -and -and (msDS-UserPasswordExpiryTimeComputed -lt $expirtyAlertDate)
    $adProperties = @('PasswordLastSet', 'pwdLastSet', 'msDS-UserPasswordExpiryTimeComputed', 'EmailAddress')

    $users = Get-ADUser -SearchBase $SearchBase -Filter $filter -properties $adProperties 
    $nearExpiryUsers = $users | Select-Object -Property Name, UserPrincipalName, SamAccountName, EmailAddress, 
            GivenName, Surname, PasswordLastSet, pwdLastSet, 'msDS-UserPasswordExpiryTimeComputed', 
            @{Name="PasswordExpirtyTimeComputed"; Expression={[datetime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')}},
            DistinguishedName
   
    foreach ($user in $nearExpiryUsers)
    {
        $remainingDays = New-TimeSpan -Start $dateNow -End $user.PasswordExpirtyTimeComputed
        $to = $user.EmailAddress
        if ([string]::IsNullOrEmpty($to))
        {
            $to = $user.UserPrincipalName
        }

        $subject = "Notification: Your password will expire in $($remainingDays.Days) Days"

        $body = @"
            <style>
                p {
                    margin: auto;
                    width: 75%;
                    border: 1px solid coral;
                    padding: 10px;        
                    border-width: thin;
                    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                }
            </style>
            <p style='background-color: coral; text-align: center; color: white; font-size: large;'>
                <strong>Active Directory Auditor Report</strong>
            </p>
            <p>
                <br>
                <strong>Automated message system
                <br>
                Your User Account Password Expiration Notification!</strong> 
                <br><br>
                Hi $($user.GivenName),
                <br><br>
                You are receiving this email because your password for user account '<b>$($user.SamAccountName)</b>''
                will expire in <b>$($remainingDays.Days)</b> days(s) on date <b>$($user.PasswordExpirtyTimeComputed.ToLongDateString())</b>. 
                Consider changing your password as earliy as possible to avoid logon problems.
                <br><br>
                To reset user account password press Ctrl+Alt+Delete keys in combination on the keyboard 
                and choose option 'Change a password'.
                <br><br>
                For any issue related to user account passwords, Please raise a request on <a href='http://vcloud-lab.com'>helpdesk portal</a>.
                <br><br>
                Thank you
                <br>
                Helpdesk Team
                <br>
                <i><strong>Phone No:</strong> 111-111-1111</i>
                <br>
                <i><strong>Email us:</strong> admin@vcloud-lab.com</i>
                <br><br>
                <span style='display: block; text-align: right; font-size: 12px;'>Please do not reply to no-reply@vcloud-lab.com email, it is not monitored!</span>
            </p>
            <hr style='width: 75%; height:1px;border:none;color:gray;background-color:gray;' />
            <p style='font-size: 12px; color: gray; text-align: right;'>
                This notification message was sent by ADReport Tool from http://vcloud-lab.com
            </p>
"@
        try
        {
            Send-MailMessage -From $From -to $to -Subject $Subject -Body $Body -BodyAsHtml -SmtpServer $SMTPServer -Port $SMTPPort -ErrorAction Stop #-UseSsl -Credential (Get-Credential) #-Attachments $Attachment <#-Cc $Cc#>
            Write-Host "$($user.Name): Email notification sent" -BackgroundColor DarkGreen
        }
        catch
        {
            Write-Host "$($user.Name): $Error[0].Exception.Message" -BackgroundColor DarkRed
        }
    }
}
end{}

Int the output it will show the failed and successful email sent on the console.

Useful Articles

PART 1 : INSTALL ACTIVE DIRECTORY DOMAIN CONTROLLER ON VMWARE WORKSTATION
PART 2 : CONFIGURE AND PROMOTE ACTIVE DIRECTORY DOMAIN CONTROLLER ON VMWARE WORKSTATION
PART 3 : CREATING NEW USERS IN ACTIVE DIRECTORY FOR VMWARE VSPHERE LAB

PART 4 : CONFIGURING DNS SERVER FOR VMWARE VSPHERE LAB
Push SSL certificates to client computers using Group Policy

PART 1 : INSTALLING ADMT TOOL (ACTIVE DIRECTORY MIGRATION TOOL)
PART 2 : MIGRATE ACTIVE DIRECTORY USERS TO ANOTHER DOMAIN USING ADMT
PowerShell: Copy group membership from one user to another user in Active Directory
PowerShell GUI: Copy group membership from one user to another user in Active Directory
PowerShell Active Directory: Sync group membership from one user to another user and move to OU

Go Back



Comment

Blog Search

Page Views

11389454

Follow me on Blogarama