Tuesday, April 19, 2016

PowerShell: Disable, Move, Delete AD Computer Objects

PowerShell: Disable, Move, Delete AD Computer Objects

Problem

Stale computer objects being left behind in an Active Directory environment. 

Solution

This PowerShell script will resolve the problem.  It was written to search a specific OU and sub OU’s to find stale records.  Stale records are defined in the script as a computer that has not changed its password in greater than 4 months and has also not logged into the domain in greater than 4 months.  Both are configurable in the script.  It will then disable the computer, move it to a specified OU, and tag the description with the date that it was disabled for future reference.  I will go into detail on usage below.

Download Script

Download

CommandLine Options

This script must be called from the PowerShell shell.  It has 4 switches to enable different portions of the script.  By default, I have turned on –WhatIF on any actions that may cause issue in an environment.  –Force turns off –WhatIF on those commands as shown below   

-MoveAlreadyDisabled will MOVE already Disabled computers in a specified source OU ($DisableSourceOU) to a specified target OU ($DisableTargetOU).

-DisableAndMove will MOVE and DISABLE Enabled Computers in a specified source OU ($DisableSourceOU) to a specified target OU ($DisableTargetOU) based on criteria.  (Read Notes area)

-DeleteDisabled will DELETE already Disabled computers based on criteria and OU. ($DisableTargetOU) (Read Notes area)

-Force Will Turn Off -WhatIF where -WhatIF is defined (-WhatIF:$True is on by Default)

 

As each section is turned on they will create output files in C:\Scripts

 

Parts of the Script to Modify

$DisableSourceOU – This is the OU you want the script to Scan and look for stale records

$DisableTargetOU – This is the OU you want the script to place the stale OU

Change the (-x) after AddMonths to your desired time from current date (-4 goes in the past 4 months if you want to go in the future remove the - sign . 

1.       $DisableComputers = get-adcomputer -properties * -filter {enabled -eq "True"} -SearchBase $DisableSourceOU -SearchScope Subtree | where {($_.lastLogonDate -lt (get-date).AddMonths(-4)) -and ($_.passwordlastset -lt (get-date).AddMonths(-4)) }

2.       $DeleteComputers = get-adcomputer -properties * -filter {enabled -eq "False"} -searchbase $DisableTargetOU -SearchScope Subtree  | where { $_.Modified -lt (get-date).AddMonths(-1) }