Cleanup · 1 tool

Stale Active Directory computer accounts

Summary

Finds computer accounts that have not logged on to the domain for 90 days, with their OU and operating system, so you can disable them before they are deleted.

Implementation

Choose your tool. Your choice is remembered on other samples.

ActiveDirectory module
Import-Module ActiveDirectory
# lastLogonTimestamp replicates every 9 to 14 days, so treat 90 days as approximate
$stale = Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 90.00:00:00 |
  Where-Object Enabled |
  Get-ADComputer -Properties OperatingSystem, LastLogonDate, Description, DistinguishedName
$stale | Select-Object Name, OperatingSystem, LastLogonDate, Description,
  @{ n = "OU"; e = { $_.DistinguishedName -replace "^CN=[^,]+," } } |
  Export-Csv .\stale-computers.csv -NoTypeInformation

# After review, disable and move them:
# $stale | Disable-ADAccount
# $stale | Move-ADObject -TargetPath "OU=Disabled Computers,DC=contoso,DC=com"

Prerequisites

  • RSAT ActiveDirectory module
  • Read access to the domain

Output

CSV of stale computers. The disable line is commented out on purpose.

Contributors

AuthorRole
Priyanshu UpadhyaySolution Architect, Microsoft 365 and Azure
Disclaimer. These samples are provided as is, without warranty of any kind. Read and test every script in a non-production tenant before you run it, and run reports before any command that changes or deletes data.