Auditing: Reset Passwords That Expire Today

The below can be run as a scheduled task to detect Active Directory User accounts that have passwords that expire today. Any objects where the password is due to expire today will automatically have the “Change password at next logon” ticked meaning that they wont suddenly lose connection to things such as mapped drives at the original expiry time.

Credit to Andrew Lyonette for turning my “Why dont you solve it like this” in to the script below.
https://www.linkedin.com/in/andylyonette/

#Searchbase
$Searchbase = "Insert Searchbase Here"

$ExpiresInDays = 1

$Users = Get-ADUser -Filter * -SearchBase $Searchbase -Properties PasswordExpired,PasswordNeverExpires | Where-Object {$_.Enabled -eq "True"}
$ExpiredUsers = @()
foreach ($User in $Users)
{
if ($User.PasswordExpired -eq "True")
{
Set-AdUser -Identity $User -ChangePasswordAtLogon $True -whatif
$ExpiredUsers += $User
}
elseif ($User.PasswordNeverExpires -ne "True")
{
$AccountFGPP = Get-ADUserResultantPasswordPolicy $User
if ($AccountFGPP -ne $null)
{
$MaxPasswordAgeTimeSpan = $AccountFGPP.MaxPasswordAge
}
else
{
$MaxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
}
$Today = Get-Date
$Expireson = (Get-ADUser -identity $User -properties PasswordLastSet).PasswordLastSet + (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
$DaysToExpire=[math]::round((New-TimeSpan $(Get-Date -Month $($Today).Month -Day $($Today).Day -Year $($Today).Year) $(Get-Date -Month $($ExpiresOn).Month -Day $($ExpiresOn).Day -Year $($ExpiresOn).Year)).TotalDays)

if ($DaysToExpire -lt $ExpireInDays)
{
Set-AdUser -Identity $User -ChangePasswordAtLogon $True -WhatIf
"$user"
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: