Powershell - 格式化正文信息输出以通过电子邮件发送

Powershell - formatting output of body info for sending via email

我遇到了一个问题,我检索了特定文件夹中的文件列表。工作正常!。我现在正尝试在电子邮件正文中对其进行格式化。 数据列的第一列很好,但第三列是文件大小(我想右对齐)一直出现问题。

我已经按照网络上的建议尝试了多种不同的格式设置选项,但似乎没有任何效果。

这是程序的主要部分:

 #Get List of files in Rejected Folder
    $files = (Get-ChildItem -Path $path -Recurse| Where-Object {     !$_.PSIsContainer }) 

    #Setup eMail properties
    $From = "xxxxxx@yyyyyy.zzz"
    $To = "bbbbbbbbb"
    $Subject = "Files in TEST Reject Folder"
    $SMTPServer = "mail.nswhealth.net"
    $SMTPPort = "25"

#Setup the Body of the eMail which will include header and list of files in Rejected Folder
    $Body = "Here is a list of the files: <p>"
    $mailBody = "Filename  `t`t`t`t`t`tCreationTime `t`t`t  Size`r`n"
    $mailBody += "------------ `t`t`t`t`t`t-----------------`t`t`t  -----`r`n"

    $Count = 0  #Initialise counter
#Get list of files and append into string with 1 file per line
    foreach ($file in $files) { 
      $kb = ($([math]::Round($file.Length / 1kb)) -as [string]).ToString().Trim();
      #$kb1 = $kb + "KB"
      #$varLine1 = $file.Name + "`t" + $file.CreationTime + "{0,15}" -f $kb1 +     "`r`n"
  #Reformat Date 
      $varDate = $file.CreationTime
      $varDate1 = $varDate.ToString("dd/MM/yyyy hh:mm tt")
      #$varLine1 = $file.Name + "`t" + $varDate1 + "{0,15}" -f $kb + "`r`n"
      #$varLine1 = $file.Name + "`t" + $varDate1 + "`t" + $kb + " KB" + "`r`n"
      $varLine1 = "{0,-50} {1,2} {2,-19} {3,2} {4,15} {5,3} {6,4}" -f     $file.Name, "`t", $varDate1, "`t", $kb, "KB", "`r`n"
      $mailBody += $varLine1;
      $Count++;    #increment counter
    }
#When complete list has been setup in body, add a total file counter to the end
    $mailBody += "`r`nTotal Number of Files: " + $Count

#Send 
    $smtp = new-object Net.Mail.SmtpClient($SMTPServer)
    $smtp.Send($From, $To, $Subject, $mailBody)

我附上了它的外观图片,不确定它是否显示 ok.But 这是它外观的模型。如您所见,前两列没问题,但第三列总是略有偏差(不能像我在电子邮件中收到的那样完全模拟)

文件名创建时间大小 ---------- ------------------ ----- 000000AB0001.ref 2015 年 10 月 11 日 05:00 下午 86 KB
0113585H0000.ref 2015 年 5 月 15 日 03:10 下午 152 KB
0264621J0000.ref 2015 年 5 月 15 日 02:50 下午 125 KB

enter image description here

如有任何帮助,我们将不胜感激 安德鲁

我认为,您需要使用 pre 标签将预先格式化的文本包含到您的电子邮件中:

$mailBody = -join @(
    'Here is a list of the files: <p>'
    '<pre>'
    $files|Format-Table -AutoSize `
    -Property @{Label='Filename';Expression='Name'},
              @{Expression='CreationTime';Format='dd/MM/yyyy hh:mm tt'},
              @{Label='Size';Expression={"$([math]::Round($_.Length / 1kb)) KB"};Alignment='right'} |
    Out-String -Width ([int]::MaxValue)
    '</pre>'
    "Total Number of Files: $($files.Count)"
)

您的格式正确(就间距而言)。如果您尝试使用等宽字体来查看消息,您会看到:

000000AB0001.ref                                         10/11/2015 05:00 PM               186  KB   

因此设置电子邮件客户端使用等宽字体或使用电子邮件客户端猫理解的标记:HTML、BBCode 等。PetSerAl 给出了一个很好的例子 HTML 电子邮件,其中正文使用 Format-Table cmdlet 格式化并放置在 pre 标签内。