rss logo

Get a list of computers that are no longer used in an Active Directory domain

PowerShell logo

Intro

As time goes by, on an Active Directory, it becomes inevitable to find yourself with parasitic computers and users objects. By parasites I mean the fact that they are no longer used in the company (computers and/or users physically destroyed, stolen, lost, gone etc…).

In this case it could be good to clean up our AD, but the question is : how to recover a list of computers and users that are no longer used in a AD domain?

The purpose of this article is to see how to obtain a list of computers and/or users that have not been connected to the domain for a predefined number of days using PowerShell.

Get AD Users or Computers

First thing to know is how to get AD users or computers list.

  • From a Domain Controller open a Windows PowerShell console :
PowerShell | Open PowerShell Console as administrator

Computers

  • Enter this command to get all the computers :
PS C:\ > (Get-ADComputer -Filter '*').Name
  • Enter this command to get all the computers whose name starts with PC :
PS C:\ > (Get-ADComputer -Filter 'Name -Like "PC*"').Name
  • Output :
PowerShell | get computers name

Users

  • Enter this command to get all the users :
PS C:\ > (Get-ADUser -Filter '*').SamAccountName
  • Output :
PowerShell | get users name

Get AD Users or Computers LastLogon

  • To know the date that object has been seen for the last time we will use the LastLogonTimeStamp property :
PS C:\ > $user = "e.cartman"
PS C:\ > Get-ADUser "$user" -Properties LastLogonTimeStamp
  • Output :
PowerShell | Get-ADUser and Get-ADComputer output
  • As we can see we cannot use the raw information retrieved. We need to use [DateTime]::FromFileTime to convert to human readable format :
PS C:\ > [DateTime]::FromFileTime((Get-ADUser "$user" -Properties LastLogonTimeStamp).LastLogonTimeStamp)
  • This is better :
PowerShell | Print LastLogon date

Get Results

We now have everything we need to list our computers or users.

  • Let's say we want the list of Computers which hasn't been seen for 120 days :
PS C:\ > $days = 120
PS C:\ > Get-ADComputer -Filter '*' -Properties LastLogonTimeStamp | where { ($(Get-Date)-[DateTime]::FromFileTime($_.LastLogonTimeStamp)).Days -gt $days } | Select-Object Name
PowerShell | List old computers objects
  • Let's say we want the list of Users which hasn't been seen for 120 days :
PS C:\ > $days = 120
PS C:\ > Get-ADUser -Filter '*' -Properties LastLogonTimeStamp | where { ($(Get-Date)-[DateTime]::FromFileTime($_.LastLogonTimeStamp)).Days -gt $days } | Select-Object Name
PowerShell | List old users account

References

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Contact :

contact mail address