DPDPOWERED83
DPDPOWERED83

Reputation: 11

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

Upvotes: 0

Views: 929

Answers (2)

DPDPOWERED83
DPDPOWERED83

Reputation: 11

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

Upvotes: 1

Smorkster
Smorkster

Reputation: 357

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.

Upvotes: 0

Related Questions