Skip to content

Instantly share code, notes, and snippets.

@LaurCzT
Created March 30, 2024 10:29
Show Gist options
  • Save LaurCzT/edbe40bb15f69acc3e06a34f2ab046b4 to your computer and use it in GitHub Desktop.
Save LaurCzT/edbe40bb15f69acc3e06a34f2ab046b4 to your computer and use it in GitHub Desktop.
PowerShell script to send reminder of password expire to all user in Active Directory
# Function to send email notification
function Send-Email {
param (
[string]$recipient,
[string]$subject,
[string]$message
)
# SMTP Configuration
$smtpServer = "your_smtp_server"
$smtpPort = 587 # or your SMTP port
$smtpUsername = "your_smtp_username"
$smtpPassword = "your_smtp_password"
# Email Content
$sender = "your_sender_email"
$email = New-Object System.Net.Mail.MailMessage($sender, $recipient, $subject, $message)
$client = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
$client.EnableSsl = $true
$client.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword)
# Send email
$client.Send($email)
}
# Function to check if user is a member of Administrators group
function Is-MemberOfAdministrators {
param (
[string]$username
)
$group = Get-LocalGroup -Name "Administrators"
return (Get-LocalGroupMember -Group $group).Name -contains $username
}
# Function to check password last change
function Check-PasswordChange {
param (
[string]$username,
[int]$daysThreshold,
[string]$domain
)
# Get user's password last set date and check if user is disabled
$user = Get-ADUser -Identity $username -Properties PasswordLastSet, Enabled
if ($user -ne $null -and $user.Enabled) {
$pwdLastSet = $user.PasswordLastSet
$daysSinceChange = (Get-Date) - $pwdLastSet
# Check if user is a member of Administrators group
if (-not (Is-MemberOfAdministrators -username $username)) {
# Send reminder email if threshold exceeded
if ($daysSinceChange.Days -gt $daysThreshold) {
$subject = "Password Expiry Reminder"
$message = "Dear $username,\n\nThis is a reminder to change your password as it has not been updated for $($daysSinceChange.Days) days, and it will expire in 10 days."
Send-Email -recipient "$username@$domain" -subject $subject -message $message
Add-Content -Path "log_sent.txt" -Value "$username: Password change reminder email sent."
}
}
} else {
Write-Host "User not found, disabled, or in Administrators group: $username"
Add-Content -Path "log_sent.txt" -Value "$username: User not found, disabled, or in Administrators group."
}
}
# Fetch all usernames from Active Directory along with the domain
$users = Get-ADUser -Filter * -Properties SamAccountName, UserPrincipalName | Select-Object SamAccountName, UserPrincipalName
# Check password change for each user
foreach ($user in $users) {
$username = $user.SamAccountName
$domain = $user.UserPrincipalName.Split('@')[1]
Check-PasswordChange -username $username -daysThreshold 50 -domain $domain
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment