Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Last active July 15, 2025 17:03
Show Gist options
  • Save NiceRath/5c08615592ed6eedfaaad5750e12a9e6 to your computer and use it in GitHub Desktop.
Save NiceRath/5c08615592ed6eedfaaad5750e12a9e6 to your computer and use it in GitHub Desktop.
Powershell script to query a list of active AD-Users which password will expire soon or has expired
# Powershell script to query a list of active AD-Users which password will expire soon or has expired
Import-Module ActiveDirectory
$SearchBase="OU=<OU>,DC=<domain>,DC=<dc>"
$users = get-aduser -SearchBase $SearchBase -Filter {(enabled -eq $true) -and (passwordNeverExpires -eq $false)} -properties sAMAccountName, displayName, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress, lastLogon, whenCreated
$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
foreach ($user in $users) {
$emailaddress = $user.emailaddress
$dName = $user.displayName
$passwordSetDate = $user.PasswordLastSet
$PasswordPol = (Get-AduserResultantPasswordPolicy $user)
# Check for Fine Grained Password
if (($PasswordPol) -ne $null) {
$maxPasswordAge = ($PasswordPol).MaxPasswordAge
} else {
# No FGPP set to Domain Default
$maxPasswordAge = $DefaultmaxPasswordAge
}
#If maxPasswordAge=0 then same as passwordNeverExpires, but PasswordCannotExpire bit is not set
if ($maxPasswordAge -eq 0) {
Write-Host "$sName MaxPasswordAge = $maxPasswordAge (i.e. PasswordNeverExpires) but bit not set."
}
$expiresOn = $passwordsetdate + $maxPasswordAge
$today = (get-date)
if ( ($user.passwordexpired -eq $false) -and ($maxPasswordAge -ne 0) ) { #not Expired and not PasswordNeverExpires
$daystoexpire = (New-TimeSpan -Start $today -End $expiresOn).Days
} elseif ( ($user.passwordexpired -eq $true) -and ($passwordSetDate -ne $null) -and ($maxPasswordAge -ne 0) ) { #if expired and passwordSetDate exists and not PasswordNeverExpires
# i.e. already expired
$daystoexpire = -((New-TimeSpan -Start $expiresOn -End $today).Days)
} else {
# i.e. (passwordSetDate = never) OR (maxPasswordAge = 0)
$daystoexpire="NA"
}
if ($daystoexpire -lt 0) {
$msg = "Expired for $daystoexpire days"
} else {
$msg = "Will expire in $daystoexpire days"
}
if ( $daystoexpire -lt 14 ) {
Write-Host "$dName ($emailaddress): $msg"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment