Removing Obsolete Computer Records from Active Directory Using PowerShell (Only Windows Client Versions)
Removing Obsolete Computer Records from Active Directory Using PowerShell
Active Directory (AD) environments can accumulate obsolete computer objects over time. These stale records not only clutter the directory but can also pose security risks. This article provides a PowerShell-based approach to identifying and removing outdated computer records from Active Directory.
Identifying Obsolete Computer Accounts
The first step in cleaning up AD is to identify inactive computers based on their last logon timestamp and password last set date. Below is a PowerShell script to find obsolete devices that have not logged in for more than 60 days:
Import-Module ActiveDirectory
$DaysInactive = 60
$time = (Get-Date).AddDays(-$DaysInactive)
# Identify obsolete devices
$obsoleteDevices = Get-ADComputer -Filter {
(LastLogonTimeStamp -lt $time -and PasswordLastSet -lt $time) -and
(OperatingSystem -like '*Windows 10*' -or OperatingSystem -like '*Windows 11*' -or OperatingSystem -like '*Windows 7*' -or OperatingSystem -like '*Windows 8.1*')
} -Properties Name, OperatingSystem, SamAccountName, DistinguishedName, LastLogonTimeStamp, PasswordLastSet
# Export the results to CSV
$obsoleteDevices | Select-Object Name, OperatingSystem, SamAccountName, DistinguishedName, @{Name='LastLogonTimeStamp'; Expression={if ($_.LastLogonTimeStamp -ne 0) {[DateTime]::FromFileTime($_.LastLogonTimeStamp)} else {'Never'}}}, PasswordLastSet | Export-Csv -Path "C:\Reports\ObsoleteDevices.csv" -NoTypeInformation
Explanation of the Script
This script filters computer accounts based on their
LastLogonTimeStamp
andPasswordLastSet
attributes.It includes only Windows operating systems to ensure relevant records are identified.
The results are exported to a CSV file for further analysis.
Moving Obsolete Computers to a Disabled OU
Once identified, obsolete computers should be moved to a designated "Disabled OU" for further review before deletion. The following script moves these records:
Import-Module ActiveDirectory
$csvPath = "C:\Reports\ObsoleteDevices.csv"
$disabledOU = "OU=Disabled OU,DC=yourdomain,DC=com" # Replace with your actual OU DN
# Import devices from CSV
$devicesToMove = Import-Csv -Path $csvPath
foreach ($device in $devicesToMove) {
try {
Move-ADObject -Identity $device.DistinguishedName -TargetPath $disabledOU
Write-Host "Moved $($device.Name) to $disabledOU" -ForegroundColor Green
} catch {
Write-Host "Failed to move $($device.Name): $_" -ForegroundColor Red
}
}
Write-Host "Device move process completed." -ForegroundColor Cyan
Key Features of the Script
Reads computer objects from the CSV file generated earlier.
Moves each computer account to a predefined "Disabled OU."
Logs successful and failed operations in the console.