简体   繁体   English

Powershell - 发送包含数组的 email 消息,需要将每个项目放在新行上

[英]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.当尝试发送包含在数组中收集的文件列表的 email 时,该数组将整个列表打印在一个字符串中。 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. iRon 提供的代码片段解决了我的问题。 Below this the function I used to email a recipient that needs a list of files in a directory.在此下方是 function 我曾经使用 email 的收件人需要目录中的文件列表。 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 .您可以首先将$OFS特殊变量(输出字段分隔符)设置为<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.然后使用 [string] 类型加速器将数组转换为字符串,数组中的每个项目都位于新行上。

$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.如果您想要另一个分隔符,请注意在此之后转换 arrays ,因为它将保持为新行直到脚本结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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