Send-MailMessage Example

An example of using the Send-MailMessage to send an email and attachment

Import-module activedirectory

$Domain = (get-addomain).Forest.toupper()
$RootDSE = (Get-ADRootDSE).defaultnamingcontext
$date = get-date -uformat "%Y-%m-%d"

Search-ADAccount -LockedOut | FT Name,ObjectClass -A | out-file c:\locked_out.txt
$Attachments = "c:\locked_out.txt"

$To = "Joe Admin <joe.admin@domain.tld>" 
$From = "AD Service <ad.service@domain.tld>" 
$Subject = "All Locked Out Users - $date ($domain)"
$Attachments = $NetIDList
$SmtpServer = "smtp.domain.tld"
$Body = " All user objects that are locked out. List of NetIDs is attached."

Send-MailMessage `
    -To $To `
    -From $From  `
    -Subject $Subject `
    -Body $Body `
    -SmtpServer $SmtpServer `
    -Attachments $Attachments

Remove-Item $Attachments 

Searching AD with Directory Searcher

There will be times when the Active Directory PowerShell modules won’t work for you. For instance, if there are a lot of objects in one OU the modules may timeout before they are able to enumerate all of them.

In the event that the AD PowerShell modules aren’t fast enough, you can fall back on .Net and the DirectoryServices searcher method.

$base = New-Object DirectoryServices.DirectoryEntry("LDAP://ou=Users,ou=Dept,dc=domain,dc=tld")
$searcher =  New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot  = $base
$Searcher.PageSize  = 1000
$Searcher.SearchScope  = "subtree"

# Filter on user members of the specified group.
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user)(name=*))"

# Specify attributes to retrieve.
$Searcher.PropertiesToLoad.Add("Name") > $Null
$Searcher.PropertiesToLoad.Add("samAccountName") > $Null
$Searcher.PropertiesToLoad.Add("Memberof") > $Null

$Results =  $Searcher.FindAll()
$count = $Results.count