Move objects in active directory which have been inactive for x days.

This is just a quick script I was asked for assistance with recently. The person in question wanted to move all computers and users to defined ou’s when they were inactive for 90 days.

The script is fairly self explanatory but quite scary if you get it wrong, for that reason I’ve included the -whatif parameter to show you what will happen if you overzealously just copy and paste the code. Once you are happy it works, remove the whatif parameters.

This script relies on the powershell module for active directory, you can see if its installed as below:

I’m also aware this code is quite inefficient by searching twice, but it was the cleanest appearance I could muster to ensure the end user understands what is happening.

[sourcecode language=”Powershell”]

#Load the required Snapins
if (!(import-module "activedirectory" -ea 0)) {
Write-Host "Loading active directory module." -ForegroundColor Yellow
import-module "activedirectory" -ea Stop

foreach ($user in search-adaccount -UsersOnly -AccountInactive -TimeSpan 90.00:00:00){
move-adobject -identity $user.DistinguishedName -targetpath "OU=Old Users,DC=some,DC=domain,dc=net" -whatif

foreach ($computer in search-adaccount -Computersonly -AccountInactive -TimeSpan 90.00:00:00){
move-adobject -identity $computer.DistinguishedName -targetpath "OU=Old Computers,DC=some,DC=domain,dc=net" -whatif

Leave a Reply