Tuesday, August 27, 2013

Get Obsolete Computer Object And Move them, Using PowerShell

Using this script you will be able to get all the computer Object in your AD, read the LastloginTimeStamp

import-module activedirectory #Add Active Directory Module to powershell
cls #Clear the console
$now=Get-Date #get the current Date
$now=$now.AddMonths(-7) #7 Month Ago
$Servers=Get-ADComputer -Properties lastLogonTimestamp -Filter {lastLogonTimestamp -lt $now}| select name,@{N='lastLogonTimestamp'; E={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
#filter the returned result to store only computer objects with LastloginTimeStamp before 7 month, I will read the lastLogonTimeStamp for each computer along with the Computer Name (Note: the -lt mean Less Than) 
foreach ($SingleServer in $Servers){ # to read each object in the $Server Variable 
$ODN = Get-ADComputer -Identity $SingleServer.name -Properties distinguishedName | select distinguishedName #We will need to get each computer DN and pass it to Move-ADObject, as Move-ADObject can not read computer name, it must read DN 
Move-ADObject $ODN.distinguishedName -TargetPath "OU=Disabled Objects,DC=Domain,DC=local"

you may get an error when running this script telling Cannot validate argument on parameter 'Identity'. The argument is null. This is because the returned result from $ODN=Get-ADComputer is Null as there is no computer which have LastloginTimeStamp value match the filter.

Like it, Please comment and share :)

No comments: