You made an awesome list of old computers and now you want to delete these computers using PowerShell for the sake of cleaning up AD.

The Script

Here you go:

Import-Module ActiveDirectory

Get-Content C:\scripts\to-delete.txt | % { Get-ADComputer -Filter { Name -eq $_ } } | Remove-ADObject -Recursive -WhatIf

Explanation

Separate each action by the pipe, that’s the little thing that looks like |

active directory auditing solutions

Get-Content is where you’ll grab the information in the text file. Mine was located at C:\scripts\to-delete.txt but you can put it anywhere as long as you write out the whole path.

The Get-ADComputer -Filter is comparing the computers that are there to folders that are in your list. Don’t worry about the syntax, just trust it.

Finally, remove the ADObject using Remove-ADObject

Remove-ADObject instead of Remove-ADComputer?!

Yes. This is because it performs the same result as Remove-ADComputer but with Remove-ADObject you can add -Recrusive. Why!? Because some objects in AD have sub objects. For example, some of the computers in my list had an OU underneath it. You’ll get a nasty message if you don’t do this. It looks like this:

Remove-ADComputer : The directory service can perform the requested operation only on a leaf objectAt line:x

error: Content is protected !!