How do I find orphaned computer objects in Active Directory using PowerShell?
Solution 1:
This would give you all computer accounts that have no activity for the last 365 Days.
Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 365.00:00:00
This would sort it for you by lastlogondate.
Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 365.00:00:00 | Sort-Object lastlogondate | Ft name,lastlogondate -auto
This would give you disabled computer accounts.
Search-ADAccount -AccountDisabled -ComputersOnly
Solution 2:
Computers change their account password every 30 days by default. If a computer hasn't changed its password in an extended period of time, it means that they are no longer connected to the network.
This PowerShell script will output 2 text files. One is for disabled computers, one is for orphaned computer account objects. You must have the Active Directory PowerShell module installed.
In this example, I exclude an "Encrypted Laptops" OU, since they're mobile laptops that are disconnected for extended periods of time. You can remove that section if you don't have a similar setup
Import-Module ActiveDirectory
$Date = [DateTime]::Today
#Sets the deadline for when computers should have last changed their password by.
$Deadline = $Date.AddDays(-365)
#Makes the date string for file naming
$FileName = [string]$Date.month + [string]$Date.day + [string]$Date.year
#Generates a list of computer accounts that are enabled and aren't in the Encrypted Computers OU, but haven't set their password since $Deadline
$OldList = Get-ADComputer -Filter {(PasswordLastSet -le $Deadline) -and (Enabled -eq $TRUE)} -Properties PasswordLastSet -ResultSetSize $NULL |
Where {$_.DistinguishedName -notlike "*Encrypted Laptops*"} |
Sort-Object -property Name | FT Name,PasswordLastSet,Enabled -auto
#Generates a list of computer accounts that are disabled and sorts by name.
$DisabledList = Get-ADComputer -Filter {(Enabled -eq $FALSE)} -Properties PasswordLastSet -ResultSetSize $null |
Sort-Object -property Name | FT Name,PasswordLastSet,Enabled -auto
#Creates the two files, assuming they are not $NULL. If they are $NULL, the file will not be created.
if ($OldList -ne $NULL) {
Out-File "C:\users\marra\desktop\Old$Filename.txt" -InputObject $OldList
}
if ($DisabledList -ne $NULL) {
Out-File "C:\users\marra\desktop\Disabled$Filename.txt" -InputObject $DisabledList
}