Moving Stale Computers in Active Directory to an OU using PowerShell

Hi All,

In this blog I have a nifty one liner that will take machines based on the last they reset their domain password and move them to an OU. By default, Windows machines reset their password every 30 days.  A good indicator that a Windows computer is stale is when that account has not reset its password for a good length of time such as 90 or 120 days.  You may want to just move machines before removing them to make it easy to review them for accuracy before deletion. The following script will look for all computer accounts where the password has not been set for over 90 days and move them to an OU. To run this you will need to have the “Active Directory Module For PowerShell” installed.

The Script

Import-Module ActiveDirectory

$d = [DateTime]::Today.AddDays(-90); Get-ADComputer -Filter  ‘PasswordLastSet -le $d’ -SearchBase “OU=WhereIStoreComputers,DC=pipe2,DC=Text,DC=com”| Move-ADObject -TargetPath “OU=WhereIStoreStaleComputers,DC=pipe2,DC=Text,DC=com”

If you would like to just see what the results will be without actually moving any machines you can just add the “-whatif” of parameter as shown below.

Import-Module ActiveDirectory

$d = [DateTime]::Today.AddDays(-90); Get-ADComputer -Filter  ‘PasswordLastSet -le $d’ -SearchBase “OU=WhereIStoreComputers,DC=pipe2,DC=Text,DC=com”| Move-ADObject -TargetPath “OU=WhereIStoreStaleComputers,DC=pipe2,DC=Text,DC=com” -whatif

Of course you will have to modify this script to reflect your Domain and OU structure. All you need to do is point the searchbase to the OU where you would like the search to begin and it will also search all OUs underneath it. You will also need to change the target path to reflect the OU where you would like the machines move. You can also increase the number of days for a computer to be considered stale.

As always, with testing all scripts you will want to run this in a lab scenario first. For more information about finding stale machines you can see my other blog “Using PowerShell to find Stale Computers in Active Directory“. I hope this helps. If you have any questions or feedback, please leave a comment.

Related Links:

Using PowerShell to find Stale Computers in Active Directory

Leave a Reply

Your email address will not be published. Required fields are marked *