Tidy Up That Pesky Computers Container with PowerShell

Another customer question (they're keeping the PoSh Chap blog in business)!

By default, when a computer account is created it gets placed in the Computers container.



Now, experience tells me that some folks aren't good at moving these computers to a production OU and as they're in a container Group Policies won't be applied. 

In fact, I've heard tell of computers hanging about in this container for months! Not moving these accounts is bad form and may well impact security hardening. Very bad form, indeed.

So... how to check for computer accounts that have outstayed their welcome?

$DaysAgo = (Get-Date).AddDays(-7)

Get-ADComputer -SearchBase "CN=Computers,DC=Contoso,DC=Com" -Filter {whenCreated -lt $DaysAgo} -Properties whenCreated


Here  $DaysAgo represents a point in time that is today minus 7 days. This will be used to identify computer objects that are older than a week. 

We then use Get-ADComputer to search the computers container for computer accounts that are older than 7 days - note the filter used. We also ask for the whenCreated property, as it's not included by default.

Now, for a report on those accounts that have been around for too long:

Get-ADComputer -Searchbase "CN=Computers,DC=Contoso,DC=Com" -Filter {whenCreated -lt $DaysAgo} -Properties whenCreated |

Select-Object Name,DistinguishedName,WhenCreated |

Export-Csv -Path .\report.csv -NoTypeInformation


Finally, and drastically, a removal (not recommended):

Get-ADComputer -Searchbase "CN=Computers,DC=Contoso,DC=Com" -Filter {whenCreated -lt $DaysAgo} -Properties whenCreated |

Select-Object Name,DistinguishedName,WhenCreated |

Remove-ADComputer -Confirm


Oh, and here's how to move the default computer account creation folder:

Redirecting the users and computers containers in Active Directory domains