Link to home
Start Free TrialLog in
Avatar of CiscoAzn
CiscoAznFlag for United States of America

asked on

Is there a script to move all disabled AD accounts over to a specified OU?

I have multiple sites/OU and each one have disabled accounts that i would want to automatically move to a different OU. Is there a Powershell script for this?
Avatar of becraig
becraig
Flag of United States of America image

Here is an easy one, includes the creation of the OU in the event you do not yet have the destination OU created:
#Import AD Module
Import-Module ActiveDirectory

#Check for existence of OU and create if not present
[string] $Path = 'OU=StaleComputers,DC=domain,DC=com'
try
{
	if (!([adsi]::Exists("LDAP://$Path")))
	{
		#Create OU since it does not yet exist
		NEW-ADOrganizationalUnit “StaleComputers” –path “DC=domain, DC=com”
	}
	else { Write-Debug "OU Already Exists:  $Path" }
}
catch [Exception]    {
	return $_.Exception.Message
}


#now we proceed to check for computers
Get-ADComputer -Filter { Enabled -eq $false } | Move-ADObject -TargetPath $Path -WhatIf

Open in new window



If you already have the OU then this will work:


 $Path = 'OU=StaleComputers,DC=domain,DC=com'
Get-ADComputer -Filter { Enabled -eq $false } | Move-ADObject -TargetPath $Path -WhatIf

Open in new window


Remove the whatif to actually run.
Avatar of CiscoAzn

ASKER

What about pointing to a specific OU for the source of all the sites with the disabled accounts and the destination would the $Path. I don't want to run it for the entire domain.
ASKER CERTIFIED SOLUTION
Avatar of becraig
becraig
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I did a test and found out why it didn't work. Had to change from ADComputer to ADUser so this works perfectly thanks!
No prob, yeah I'd actually done this for computers on another question and just copy and pasted.
Did you need anything else on this question ?

If so let me know and I will be happy to help.
Avatar of Satyendra Tiwari
Satyendra Tiwari

Hi Cisco,
You can download the complete script from this given resource and I hope, it will help you to resolve your purpose for moving all disabled AD accounts to specific OU : https://gallery.technet.microsoft.com/scriptcenter/Move-and-disable-inactive-b1cf86c3
This question was indicated as answered in comment 40458167
This question was indicated as answered in comment 40458167

Ok, i did not see that.
becraig I want to run this as a scheduled task and not able to. Do you have a way to do this? What is the Action that needs to be input to have this working?