This script will list out all users with passwords older than X days. The day value is stored in the second line.
# Set the number of days to check for unchanged passwords
$daysThreshold = 90
# Prompt the user to select an Organizational Unit (OU)
$selectedOU = Read-Host "Enter the DistinguishedName of an OU (EX: OU=SUBNAME,OU=Name,DC=DOMAIN,DC=LOCAL). Leave blank to search the entire domain."
# Get the current date
$currentDate = Get-Date
# Calculate the date X days ago
$thresholdDate = $currentDate.AddDays(-$daysThreshold)
# Get users from Active Directory
if ([string]::IsNullOrEmpty($selectedOU)) {
$users = Get-ADUser -Filter * -Properties PasswordLastSet, Enabled, DisplayName, CannotChangePassword
} else {
$users = Get-ADUser -Filter * -SearchBase $selectedOU -Properties PasswordLastSet, Enabled, DisplayName, CannotChangePassword
}
# Iterate through each user and check if their password has not been changed in X days
$results = @()
foreach ($user in $users) {
if ($user.Enabled -eq $true) {
$passwordLastSet = $user.PasswordLastSet
# If PasswordLastSet is null or empty, skip the user
if (-not $passwordLastSet) {
continue
}
# Compare the last password change date with the threshold date
if ($passwordLastSet -lt $thresholdDate) {
$result = [PSCustomObject]@{
DisplayName = $user.DisplayName
SAMAccountName = $user.SamAccountName
LastPasswordSet = $passwordLastSet
CanChangePassword = -not $user.CannotChangePassword
}
$results += $result
}
}
}
# Output the results in a table format
$results | Sort LastPasswordSet | Format-Table -AutoSize
Note: You can copy the DistinguishedName of an OU easily in Active Directory Administrative Center. Navigate to the OU – click on the OU name at the very top. The DN should now be highlighted.