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
}#endif

#users
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
}

#computers
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
}
[/sourcecode]

Related Posts

New Module: Creating an RDP file password with Pow... Here's something that is surprisingly tricky to automate in this day and age. Creating a password and storing it in an RDP file. I'm not here to debat...
Dealing with multi numbered versions in powershell... So here's a quick little blog about something i discovered in powershell while googling today. Lots of vendors like to use version numbers includin...
Accurately checking the Citrix PVS “cache in... Citrix Provisioning services "Cache in RAM, overflow to disk", even with it's challenges is something I've always felt was a great idea, hell, I fores...

Leave a Reply