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

时间:2015-11-24 05:53:50

标签: email powershell smtp format

我遇到了一个问题,即我检索了特定文件夹中的文件列表。工作良好!。我现在正试图在电子邮件正文中格式化它。 数据的第一列是好的,但第三个是文件大小(我想对齐它)不断出现问题。

我已经尝试了网上建议的许多不同的格式化选项,但似乎没有任何效果。

以下是该计划的主要部分:

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

我已经附上了它看起来像的图片,不确定它是否显示好。但这里是模仿它的样子。正如你所看到的,前两列是可以的,但第三列总是略有不同(不能像我在电子邮件中那样模拟它)

文件名CreationTime大小 ------------ ----------------- ----- 000000AB0001.ref 10/11/2015 05:00 PM 86 KB
0113585H0000.ref 15/05/2015 03:10 PM 152 KB
0264621J0000.ref 15/05/2015 02:50 PM 125 KB

enter image description here

任何帮助将不胜感激 安德鲁

2 个答案:

答案 0 :(得分:1)

我认为,您需要使用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)"
)

答案 1 :(得分:0)

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

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

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

相关问题