A quick post this one.
I have recently taken on an AD structure that hasn’t had any love in a while.  Its obvious just from looking at it that plenty of computers are old and in some cases not even present anymore.  I therefore wrote a quick script to assist in helping me  find computers that hadn’t been logged onto in a certain period of time.
I decided to look at 4 intervals of 3, 6, 9 and 12 months.  I wanted PowerShell to query AD so I used the following:
Firstly I set some variables to the dates I’d decided on.  like so:

   1: $3MonthsOld = (Get-Date).adddays(-90)

   2: $6MonthsOld = (Get-Date).adddays(-180)

   3: $9MonthsOld = (Get-Date).adddays(-270)

   4: $12MonthsOld = (Get-Date).adddays(-365)

Pretty straight forward.  Get the current date and take off so many days (its not pin point accurate I know! but you get the idea).
Then I want to run a query against AD.  I use the Get-ADComputer cmdlet to query AD then throw in some filters.  In my case I know the network I’m working on has Windows 7 clients throughout so I’m going to filter by operating system.  Then I will query the last logon date and see if its less than one of the date sets i set in the variables listed above.

   1: $ListOfComputers = Get-ADComputer -Filter {OperatingSystem -Like 'Windows 7*' -and LastLogonDate -lt $3MonthsOld} -Properties *

This can be edited in many ways and using any of the previously declared date sets.  It queries AD as suggested above (i.e using the filters I specified) and grabs all the properties.  Pretty straight forward. So, what do we now do with this list.  Well there are many options.
Count them to see how many rouge machines we have?  Like so:

   1: $Count = ($ListOfComputers).count

   2: Write-Host -ForegroundColor Green "Total Computers not logged onto in 3 months $Count"

(Yeah yeah – pipe down Write-Host haters!)
We could sort them by LastLogonDate to see which ones are worse than other?

   1: ($ListOfComputers).Name | Sort LastLogonDate | FT -Autosize

We could move them to another OU?

   1: $ListOfComputers | Move-ADObject -TargetPath "OU=Disabled Computers,DC=company,DC=local"

Disable them?

   1: $ListOfComputers | Set-ADComputer -Enabled $false

Some good points here for building a tool right?
I’ve been using this today and the results for me were particularly interesting.  How do you handle AD clean ups with PowerShell?  Would love hear from you.  Comments below require approval but feel free to comment on Twitter.
Thanks for reading,