Objective: search for all disabled users who have something in the ipPhone attribute, email the results to email address.
Issue: when I receive the email, the data is not separated by user account or in a table Not sure how to correct it
Code:
#Add-WindowsFeature RSAT-AD-PowerShell
#needed for server 2012+ if no rstat tools installed on it
#Import-Module activedirectory
#Need to import modeule to read powershell
$emailto = 'markbuehler@milgard.com'
$emailfrom = 'markbuehler@milgard.com'
$emailsubject = "Disabled Users who have IpPhone Attribute Active"
$smtp_server = 'corp-smtp01.milgardwindows.com'
$disabledusers = get-aduser -SearchBase
"OU=MIMilgardUsersandComputers,DC=milgardwindows,DC=com" -Filter {(Enabled -eq $false -and
ipPhone -like "*")} -Properties * | Select-Object Name,UserPrincipalName,Office,ipPhone |
Format-Table -Property Name,UserPrincipalName,Office,ipPhone
Send-MailMessage -To $emailto -From $emailfrom -Subject $emailsubject -SmtpServer $smtp_server
-BodyasHtml ($disabledusers | Out-String)'
Email body result:
Name UserPrincipalName Office ipPhone ---- ----------------- ------ ------- Adi Rasilau
AdiRasilau@milgard.com Milgard - Sacramento 2742 Nai Jones NaiJones@milgard.com Milgard -
Sacramento 2780 Phillip Wheeler PhillipWheeler@milgard.com Milgard - Sacramento 2727 Joy
Rogers JoyRogers@milgard.com Milgard - Temecula 3286"
Since you are using Format-Table
, you need to make sure the data ends up in your HTML email either with
What you are forgetting in your Send-Mailmessage
line is that you need to send the table as Body
.
The easiest way of keeping the data as table is to wrap the table output inside <pre>..</pre>
tags so it will display with a monospaced font and newlines are kept.
I also would like to show you how to use Splatting on cmdlets that can take a lot of parameters:
# Get-ADUser by default already returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
$searchBase = "OU=MIMilgardUsersandComputers,DC=milgardwindows,DC=com"
$filter = "Enabled -eq 'false' -and ipPhone -like '*'"
$disabledusers = Get-ADUser -SearchBase $searchBase -Filter $filter -Properties Office,ipPhone
# stringify the results into a table as string and wrap inside '<pre>..</pre>' tags
$table = '<pre>{0}</pre>' -f ($disabledusers |
Format-Table -AutoSize -Property Name,UserPrincipalName,Office,ipPhone |
Out-String)
# or create a HTML table from it
# $table = $disabledusers | ConvertTo-Html -Property Name,UserPrincipalName,Office,ipPhone
# in case you do a HTML table, also create a CSS style for it so it shows up nicely formatted
# create a Hashtable for splatting
$mailParams = @{
To = 'markbuehler@milgard.com'
From = 'markbuehler@milgard.com'
Subject = 'Disabled Users who have IpPhone Attribute Active'
SmtpServer = 'corp-smtp01.milgardwindows.com'
Body = $table
BodyAsHtml = $true
# more parameters can go here
}
# send the email
Send-MailMessage @mailParams