-
Notifications
You must be signed in to change notification settings - Fork 0
/
ad_pwd_expiration_notification.ps1
64 lines (52 loc) · 2.6 KB
/
ad_pwd_expiration_notification.ps1
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
#########################################################################################
# Script to send email to Active Directory users when their password is about to expiry #
#########################################################################################
####### change only these envs ####################
$Company = # your company name
$EmailAccount = # your email account
$EmailAccountPwd = # your email account password
$EmailFrom = # your email address
$Support = # your company support email address
$PasswordNotificationStartInDays = 10
$SMTPServer = # your SMTP server address
###################################################
$SecPasswd = ConvertTo-SecureString $EmailAccountPwd -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($EmailAccount, $SecPasswd)
$Encoding = New-Object System.Text.utf8encoding
function Send-MailPasswordExpiresMessage
{
[CmdletBinding()]
Param
(
[String]$Name,
[Int]$DaysToExpire,
[String]$ToEmailAddress
)
$Subject = "Your $Company password will expire in $DaysToExpire days"
$Body = @"
<html>
<body style="font-family:calibri">
<b>Dear $Name,</b><br><br>
<b>This message is to notify you that your $Company password will expire in $DaysToExpire day(s). Please consider to change it before expires.</b>
<br><br>If you need further assistance or have questions, please contact $Support<br><br>
Thank you
</body>
</html>
"@
Send-Mailmessage -smtpServer $SMTPServer -Credential $cred -UseSsl -from $EmailFrom -to $ToEmailAddress -subject $Subject -body $Body -bodyasHTML -priority High -Verbose -Encoding $Encoding
}
# Get todays date
$Today = Get-Date
# Get list of Active Directory Users
$ADUsers = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties emailaddress,passwordlastset,msDS-UserPasswordExpiryTimeComputed
foreach ($ADUser in $ADUsers)
{
# Parse password expiry date/time
$PasswordExpiresOn = [DateTime]::FromFileTime([Int64]::Parse($ADUser."msDS-UserPasswordExpiryTimeComputed"))
$DaysToExpire = (New-TimeSpan -Start $Today -End $PasswordExpiresOn).Days
# If the days to expire are between 1 & PasswordNotificationStartInDays, send an email to the user
if (($DaysToExpire -ge '1') -and ($DaysToExpire -le $PasswordNotificationStartInDays))
{
Send-MailPasswordExpiresMessage -Name $($ADUser.Name) -DaysToExpire $DaysToExpire -ToEmailAddress $($ADUser.EmailAddress) -Verbose
}
}