active directory disable users older than x days

February 29, 2012

Script Details

This is example will show you how to disable folks that have a password older than x number of days AND / OR have not logged in for X number of days


  • ActiveRoles Management Shell (free)
  • Powershell
  • Server 2003 or Higher
  • Domain Controller

Example Script

Filename: C:\1audit\scripts\disable_accounts_password_age_greater_91_days.ps1
Description: (Disable users that have a password older than 91 days and have not logged in for at least 89 days)

Add-PSSnapin Quest.ActiveRoles.ADManagement
# Free to download  
# Original Script by Sean Kearney 
# List all users in that have not logged on within  
# XXX days in "Active Directory"  
# AND password has not been changed for
# Get the Current Date  
# Number of Days to check back (user must not have logged in for this many days)     
#Password Age (password must at least this many days old)
# Organizational Unit to search  
# Find users in OU above that are not disabled, password has not changed for # of days specified
GET-QADUSER -SizeLimit 0 -Disabled:$False –PasswordNotChangedFor $PasswordAgeDays -SearchRoot $OU |  

#And user has not logged in for at least # of days specified
where { $_.lastlogontimestamp -le (get-date).adddays(-$NumberDays) } |  

#Optionally Exclude a specific OU from Search
Where {$_.ParentContainer -notmatch "$OU='Contoso.local/Business/Users/Utility"} |  

#Uncomment This to acutally disable user

select Name, ParentContainer, Department, Office, Description, LastLogonTimeStamp, LastLogon, AccountIsDisabled, PasswordExpires, PasswordLastSet, PasswordNeverExpires | 
Export-Csv disable_accounts_password_age_greater_91_days_$date.csv -noTypeInformation 
# Add in a | DISABLE-QADUSER to AUTOMATICALLY Disable those accounts.  
# Line should read like this if you want to do that  
# GET-QADUSER -SearchRoot $OU | where { $_.lastlogontimestamp -le (get-date).adddays(-$NumberDays) } | DISABLE-QADUSER 

Create a batch file to run this script

Filename: disable_accounts_password_age_greater_91_days.bat

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -noexit -command C:\1audit\scripts\disable_accounts_password_age_greater_91_days.ps1