Thursday, June 30, 2011

PowerShell: AD Delete Non-Staged Computers

Came up with the below script to address the issue of delegated admins that don't stage their computer objects in AD. This script will delete any computer objects in the default Computer container. I scheduled a task to run every half hour that runs under an standard user account (that is a member of no admin groups but has delete access to the container). This way if the delegated admins brain dump and forget to the stage the system they don't have to call me to move it. They just have to wait a half hour before they can add it again.


#########################################################################
# Script Name: AD_Delete_Non_Staged_Computers.ps1
# Version: 1.0
# Author: Dean
# Last Edited: 06/28/2011
# Description: Deletes Non Staged Computers from Default Computers
# Container. Sends Email Report
#########################################################################


#Variable for System Count
$x = 0

#Email Message Body
$emsg = "<p>The following computer(s) were deleted from the Computers container:</p>"

#Email server
$smtpServer = "smtp.mycollege.edu"

#Get Current Short Date
$rptDate = Get-Date

#Query AD for All Computers in OU Computers Container
$objADSI = [ADSI]"LDAP://CN=Computers,DC=MYCOLLEGE,DC=EDU"
$Search = New-Object DirectoryServices.DirectorySearcher($objADSI)
$Search.filter = "(objectClass=computer)"
$Results = $Search.Findall()

#Remove Each Computer Object Listed in Results
foreach($result in $Results)
{
$x = $x + 1
$emsg = $emsg + $result.Properties["cn"][0].ToString().Trim() + "<br />"
$systemCN = "CN=" + $result.Properties["cn"][0].ToString().Trim()
$objADSI.Delete("computer", $systemCN)
}

if($x -gt 0)
{
#Settings for Email Message
$messageParameters = @{
Subject = "Deleted Computer Report " + $rptDate
Body = $emsg
From = "admins@mycollege.edu"
To = "admins@mycollege.edu"
SmtpServer = $smtpServer
}
#Send Email Message
Send-MailMessage @messageParameters –BodyAsHtml
}