Home > Active Directory, PowerShell Scripting > Move objects in active directory which have been inactive for x days.

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.


#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
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: