The LastLogon and LastLogonTimeStamp attributes can help you to decide if an Active Directory user account or computer account is active or inactive.
Powershell to find inactive accounts Active Directory for 90 days or longer.
Another Powershell script to find inactive accounts for 90 days or longer.
$domain = “example.com”
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
# Get all AD User with lastLogonTimestamp less than our time and set to enable
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp |
select-object Name,@{Name=”Stamp”; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} |
export-csv OLD_User.csv -notypeinformation
In Order to Disable a User account, use this to see what accounts you are going to be disabling:
Where-Object {$_.lastlogondate -ne $null} |
Format-Table Name,SamAccountName,LastLogonDate -AutoSize
The below powershell lists all the disabled Active Directory users:
Search-ADAccount and list the selected properties of all disabled Active Directory users:
Search-ADAccount –AccountDisabled -UsersOnly
Select -Property Name,DistinguishedName
Find Disabled Active Directory Users from specific OU:
Search-ADAccount -SearchBase “OU=TestOU,DC=TestDomain,DC=Local” –AccountDisabled -UsersOnly
Select -Property Name,DistinguishedName
In Order to Export Disabled Active Directory Users to CSV using Powershell user below cmdlet:
Search-ADAccount –AccountDisabled -UsersOnly |
Select -Property Name,DistinguishedName |
Export-CSV “C:\\DisabledADUsers.csv” -NoTypeInformation -Encoding UTF8
You can check the below cmdlets which will export data in the following order – Givenname, Surname, SamAccountname, PrimarySMTPAddress
In Order to Move Disabled Active Directory Users and Computers to New OU
Let’s assume you have two OU’s in Active Directory; DisabledUserAccounts and DisabledComputerAccounts.
Get-ADComputer -Filter ‘Enabled -eq $False’ | ForEach {Move-ADObject -Identity “$_” -TargetPath “OU=DisabledComputerAccounts,DC=domain,DC=com”} #Substitute your domain for “DC=domain,DC=com”
By following above steps you can easily find and remove Active Directory inactive user and computer accounts or you can move them to different OU by using Powershell.