Showing posts with label cleanup. Show all posts
Showing posts with label cleanup. Show all posts

Tuesday, October 27, 2015

AD and SCCM Device Cleanup

This Script Removes devices from AD and SCCM that have not been logged onto in 90days, and have not reset thier device password in 120. It then goes on to check the User device affinity to ensure Devices are sorted to the same OU as the Primary owner. (Unless that user is a member of the service desk, then leave as is. it Also maintains a complete log of all changes.
$log="C:\temp\sorter.log
$date=get-date
$oulist=Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase 'OU=DEPT,DC=Domain,DC=com' -SearchScope OneLevel #get-oulist

########################################Cleanup Stale PC's##################

$t="Starting Purge on $date"
$t|out-file $log -append


#Collect Stale devices.
Foreach ($x in Get-QADComputer -NotLoggedOnFor 90 -PasswordNotChangedFor 120 -searchroot Domain.com/Dept/){
$t="$x.name was Purged on $date"
$t|out-file $log -append 
Write-host $t
#Remove from AD/SCCM
remove-cmdevice -devicename $x.name –force –confirm:$false  
remove-qadobject $x.DN –force –confirm:$false
 
}

$t="Purge complete on $date. "
$t|out-file $log -append

############################################## Object Sorter

$t="Starting Sort on $date"
$t|out-file $log -append

#get all computers
foreach ($z in Get-qadcomputer -searchroot "Domain.com/Dept/"){
$t=""
$x=get-cmdevice -name $z.name 
if (!$x.username){ #check for Assigned user. If none log, and move on.
$t=$z.dn+" no user attached - unable to move."
write-host $t
$t|out-file $log -append

}elseif((Get-ADUser $x.Username -Properties memberof).memberof -like "CN=ISM-ALL*"){ #if member of servicedesk, dont touch 

$t=$z.dn+" last used by service desk. Do not move.."
write-host $t
$t|out-file $log -append

}else{
$y=get-qaduser $x.UserName;

$f=$z.name.lenght+16
$G=$y.displayname.length+14
$zdn= $z.dn.substring($f)
$ydn= $y.dn.substring($g)
#write-host $f $zdn 
if($zDN -match $ydn){ #if user dn and PC dn match - move on.
 write-host $z.name " is properly located"
 $zdn=""
 $ydn=""
}else{
 $zdn=""
 $ydn=""
#sort based on DN.

Foreach ($q in $OUlist){
$q.Name
if ($y.DN -match $q.name){write-host "yes";$dept=$q.name}
}

$newou="Domain.com/Dept/"+ $dept +"/Computers"
$t=$z.dn+" moved to "+$newou
write-host $t
$t|out-file $log -append
Move-QADObject $z.dn -NewParentContainer $NewOU
$NewOU=""
}#end move if
}#end no user if
}#end dn match if