Over time, in an Active Directory, it becomes inevitable to end up with parasitic computers and users objects. By parasites, I simply mean that they are no longer used in the company (computers and/or users physically destroyed, stolen, lost, gone etc…).
In this case, it may be worth cleaning up our Active Directory, but the question is: how do we get a list of computers and users no longer in use in an AD domain?
The aim of this article is to show yo how to obtain a list of computers and/or users who have not logged on to the domain for a predefined number of days, using PowerShell.
The first thing you need to know is how to obtain a list of AD users or computers.
PS C:\ > (Get-ADComputer -Filter '*').Name
PS C:\ > (Get-ADComputer -Filter 'Name -Like "PC*"').Name
PS C:\ > (Get-ADUser -Filter '*').SamAccountName
PS C:\ > $user = "e.cartman"
PS C:\ > Get-ADUser "$user" -Properties LastLogonTimeStamp
PS C:\ > [DateTime]::FromFileTime((Get-ADUser "$user" -Properties LastLogonTimeStamp).LastLogonTimeStamp)
We now have everything we need to compile a list of our computers or users.
PS C:\ > $days = 120
PS C:\ > Get-ADComputer -Filter '*' -Properties LastLogonTimeStamp | where { ($(Get-Date)-[DateTime]::FromFileTime($_.LastLogonTimeStamp)).Days -gt $days } | Select-Object Name
PS C:\ > $days = 120
PS C:\ > Get-ADUser -Filter '*' -Properties LastLogonTimeStamp | where { ($(Get-Date)-[DateTime]::FromFileTime($_.LastLogonTimeStamp)).Days -gt $days } | Select-Object Name
Contact :