Home > Software engineering >  PowerShell to delete AD Object based on timestamp?
PowerShell to delete AD Object based on timestamp?

Time:08-19

How can I delete all the ADObject (AD User / AD Computer object) in a specific OU and below based on the specific Modified time?

Starting OU location Canonical Name:

Domain.com/OffBoarded Users
Domain.com/Old Computers

Using this command: https://docs.microsoft.com/en-us/powershell/module/activedirectory/remove-adobject

CodePudding user response:

Start by getting the AD objects you want to remove, then pipe it to the remove command.

Get-ADObject command: https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-adobject?view=windowsserver2022-ps

Look at example 2's "Search Base" and example 3's "specified attribute"

Sample:

$date = (Get-Date).AddDays(-30)
Get-ADObject -SearchBase 'CN=Offboarded Users,DC=Domain,DC=Com' -searchScope 2 -filter "whenChanged -le $date" | Remove-ADObject
Get-ADObject -SearchBase 'CN=Old Computers,DC=Domain,DC=Com' -searchScope 2 -filter "whenChanged -le $date" | Remove-ADObject
  • Related