Wednesday, November 5, 2008

Powershell: New Active Directory Objects Report

Here's a quick Powershell script to send you a report of the most recent additions to Active Directory.

### --------------------------------------------
### Written by Matt Brown - 12:13 PM 10/22/2008
###
### AD Report on new objects created in the
### last 24 hours
### Requires Quest Powershell extenstions for AD
### --------------------------------------------

#######################################
####### Load Required Snapin's ########
#######################################
## Add Quest AD Snapin Tool
$addAD = 1
get-PSSnapin * | foreach {
if($_.Name -match 'quest.activeroles.admanagement') {
$addAD = 0
}
}
if($addAD) { add-PSSnapin quest.activeroles.admanagement }

#######################################
########### Setup Log File ############
#######################################
$Today=get-date
$filename="NewADObjects_"+($Today.year).ToString()+"_"
$filename+=($Today.month).ToString()+"_"+($Today.day).ToString()+".txt"

#######################################
### Get AD Formated Date 24 hrs ago ###
#######################################
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$creationDate = $currentDateUtc.AddHours(- 24)
$YYYY = $creationDate.Year.ToString()
$MM = $creationDate.Month.ToString();
if ($MM.Length -eq 1) {$MM="0" + $MM};
$DD = $creationDate.Day.ToString();
if ($DD.Length -eq 1) {$DD="0" + $DD};
$creationDateStr = $YYYY + $MM + $DD + '000000.0Z'

$MsgBody = "###################`n"
$MsgBody += " New AD Objects`n"
$MsgBody += "###################`n`n"

write-host $creationDateStr
$newobjects = Get-QADObject -ldapfilter "(whenCreated>=$creationDateStr)"
-SizeLimit 30000 | sort type

if($newobjects) {
$newobjects | out-file $filename
$type = ""
$newobjects | foreach {
if($_.Type -eq $type) {
$MsgBody += " " + $_.Name + "`n"
} else {
$type = $_.Type
$MsgBody += "`nNew " + $_.Type + "(s)`n"
$MsgBody += "===================================`n"
$MsgBody += " " + $_.Name + "`n"
}
}
}

#######################################
############ Email Report #############
#######################################

function SendEmail($body) {
$message = New-Object System.Net.Mail.MailMessage
$message.From = "myemail@domain.com"
$message.To.Add("myeamail@domain.com")
$message.Subject = "Active Directory - new object report"
$message.Body = $body

$smtp = New-Object System.net.Mail.SmtpClient
$smtp.Host = "smtp.mailserver.com"
$smtp.UseDefaultCredentials = $true
$smtp.Send($message)
}

SendEmail($MsgBody)

1 comment: