简体   繁体   中英

Powershell - Sending email message that contains an array, need to have each item on a new line

When attempting to send an email containing a list of files collected in an array, the array prints out the entire list in one string. The goal is have the list of files found printed on a new line for each item.

function SendReport
{
    $rptDataPath = "C:\Maintenance\Logs\"
    [array]$rptData = Get-ChildItem -Path "$rptDataPath" | select Name | Out-String
    $smtpBody = "Below are the following files located in $rptDataPath <br><br> $rptFileList"
    Send-MailMessage -SmtpServer $smtpServer -To $smtpRecipient -From $smtpSender -Subject $smtpSubject -Body $smtpBody -BodyAsHtml
}
SendReport

The code snippet provided by iRon resolved my issue. Below this the function I used to email a recipient that needs a list of files in a directory. Thank you for your help.

$smtpServer = "<Mail Server>"
$smtpRecipient = "Recipient Address"
$smtpSubject = "PowerShell Reporting HTML Example"
$smtpSender = "From or Spoofing Address"
function SendReport
{
    $rptDataPath = "<Directory Path>"
    $rptData = (Get-ChildItem -Path "$rptDataPath").name -join '<br>'
    $smtpBody = "Below are the following files located in $rptDataPath <br> $rptData"
    Send-MailMessage -SmtpServer $smtpServer -To $smtpRecipient -From $smtpSender -Subject $smtpSubject -Body $smtpBody -BodyAsHtml
}
SendReport

You can first, set the $OFS special variable (Output Field Sperator), to <backtick>n . Then use the [string] type accelerator to convert the array to a string with each item in the array on a new row.

$smtpbody = "Files: $( $ofs = "`n"; [string]$rptdata ) "

Though be careful to convert arrays after this if you want another separator, as it will stay as new line until script ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM