Powershell to disable unused computer AD accounts.

Here is a powershell script that can be used to cleanup old computer AD accounts:


Import-Module ActiveDirectory

$date = get-date

$systems = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 365

foreach($computer in $systems){

$computer | select-object Name, OperatingSystem, DistinguishedName, LastLogonTimeStamp >> “C:\Scheduled Tasks\AD Cleanup\SystemInfo.csv”

$computer | disable-adaccount

$computer | move-adobject -targetpath “ou=Dormant Computers,dc=xxxx,dc=xxx”

write-host “$computer will be moved to Dormant computers”

}

First we load the Active Directory Module into Powershell. This has to be added as a Winodws Feature first.
Then we search the AD for all computer accounts which have been inactive for the last 365 days.
In the foreach loop we write the name of the server and LastLogonDate to a csv file to keep as a log.
Then we disable the account and move it to a OU where we keept disabled accounts.
Last we output a stsus message to the console.

Staffan Olofsson

Advertisements

4 thoughts on “Powershell to disable unused computer AD accounts.

  1. Doikk

    Do not use this, it started disabling and moving all of my computers, not just inactive ones. Find a different script that gives you the list of what it will do first.

    Reply
    1. sqlsos Post author

      Hello. I would start by saying that you should of course not run any scripts from the net before testing and understanding the functionallity fully. Commenting out the two rows that disables and actually moves the account’s would have been a good approach. In this case there was actually a typo in the script that affected results set. The third row should look like this;
      $systems = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 365

      Reply
  2. Michel Jon

    Excellent, this is very helpful to disable unused computer active directory account but I found automate active directory clean from http://activedirectorycleanup.hatenablog.com/ to identify inactive or old computer accounts that have been inactive for 180 days. It helps to clean inactive computer accounts and view report means what actions have been taken for inactive accounts.

    Reply

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