-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADPasswordExpirationNotificationScript.ps1
47 lines (40 loc) · 2.41 KB
/
ADPasswordExpirationNotificationScript.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
Import-Module ActiveDirectory
$SmtpServer = "your_smtp_server"
$FromAddress = "[email protected]"
$UseCredentials = $true # set to $false if you do not want to use Office 365 credentials
$Username = "your_office365_username"
$Password = ConvertTo-SecureString "your_office365_password" -AsPlainText -Force
$PasswordExpiryThresholds = @(10, 5, 1) # days before password expiry
# Get all users in Active Directory
$Users = Get-ADUser -Filter * -Properties "msDS-UserPasswordExpiryTimeComputed"
# Loop through each user
foreach ($User in $Users) {
# Get the password expiry time
$PasswordExpiryTime = [DateTime]::FromFileTime($User."msDS-UserPasswordExpiryTimeComputed")
# Check if the password is going to expire soon
foreach ($Threshold in $PasswordExpiryThresholds) {
if (($PasswordExpiryTime -lt (Get-Date).AddDays($Threshold)) -and ($PasswordExpiryTime -gt (Get-Date))) {
# Send an email to the user
$ToAddress = $User.EmailAddress
$Subject = "Your password is going to expire in $Threshold days"
$Body = "Your password is going to expire on $PasswordExpiryTime. Please change your password to ensure continuous access to your account."
if ($UseCredentials) {
Send-MailMessage -SmtpServer $SmtpServer -From $FromAddress -To $ToAddress -Subject $Subject -Body $Body -UseSsl -Port 587 -Credential (New-Object System.Management.Automation.PSCredential($Username, $Password))
} else {
Send-MailMessage -SmtpServer $SmtpServer -From $FromAddress -To $ToAddress -Subject $Subject -Body $Body -UseSsl -Port 587
}
}
}
# Check if the password has already expired
if ($PasswordExpiryTime -lt (Get-Date)) {
# Send an email to the user
$ToAddress = $User.EmailAddress
$Subject = "Your password has expired"
$Body = "Your password has expired on $PasswordExpiryTime. Please change your password as soon as possible to regain access to your account."
if ($UseCredentials) {
Send-MailMessage -SmtpServer $SmtpServer -From $FromAddress -To $ToAddress -Subject $Subject -Body $Body -UseSsl -Port 587 -Credential (New-Object System.Management.Automation.PSCredential($Username, $Password))
} else {
Send-MailMessage -SmtpServer $SmtpServer -From $FromAddress -To $ToAddress -Subject $Subject -Body $Body -UseSsl -Port 587
}
}
}