Local Tech Repair: Powershell/LDAP finding all never expiring users in Active Directory (AD)

Monday, November 17, 2014

Powershell/LDAP finding all never expiring users in Active Directory (AD)

Another very useful powershell script that pulls all the users that are set their password to never expire. 


One key thing on this script is making sure that you filter out service accounts because you don't need them every single time. so for instance if your employee numbers allways start with a E then you could add (employeeID=e*) to the ldap filter. and this will pull only employeeID field from ad with the employee ID that starts with * 

<# 
Created by Local Tech Repair Admin
Date: 10/31/2014
version: .01
requires the activedirectory modele please run
import-module ActiveDirectory -WarningAction silentlyContinue

takes all user accounts that employee id that starts with a e and has never expire password checked.
#>


$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$start = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds

Write-Output "first_name,last_name,email_address,employee#" |  out-file .\users.csv -force
$server = "yourdomaincontroler"
$root = [ADSI]"LDAP://OU=Accounts,DC=domain,DC=local"
$search = [adsisearcher]$root
$Search.Filter = "(&(objectCategory=person)(sAMAccountType=805306368)(employeeID=e*)(userAccountControl:1.2.840.113556.1.4.803:=65536))"
$colResults = $Search.FindAll()

foreach ($i in $colResults)
{
 [string]$i.Properties.Item('givenName'),[string]$i.Properties.Item('sn'),[string]$i.Properties.Item('mail'),[string]$i.Properties.Item('samaccountname') -join "," |  out-file .\users.csv -append
}

Write-Output "Done - output to users.csv"
$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$end = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
$completed = $end - $start
Write-Output "Done - output to users.csv - Finished in seconds" $completed



Hopefully this helps you keep track of everyone that has never expiring passwords and then you can get them so they don't . no reason to have exceptions for users in your password policy. As this only increases the risk to your company. 
LDAP note using (sAMAccountType=805306368) is faster than using (objectclass=user)

-Local Tech Repair Admin

remember share if you find this useful. Sharing is caring and link back to me for some credit :D