使用 send-mailmessage 使用 powershell 格式化电子邮件

Email formatting with powershell using send-mailmessage

Objective: 搜索所有ipPhone属性有问题的禁用用户,将结果发邮件到邮箱。

问题:当我收到电子邮件时,数据未按用户帐户分隔或 table 不确定如何更正它

代码:

#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)'

电子邮件正文结果:

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"

由于您使用的是 Format-Table,因此您需要确保数据最终出现在您的 HTML 电子邮件中 ​​

  • 等宽字体,因此它看起来与控制台中的一样
  • 格式很好 HTML table

您在 Send-Mailmessage 行中忘记的是您需要将 table 作为 Body 发送。

将数据保持为 table 的最简单方法是将 table 输出包装在 <pre>..</pre> 标签内,这样它将以等宽字体显示并保留换行符。
我还想向您展示如何在可以采用大量参数的 cmdlet 上使用 Splatting

# 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