Send-MailMessage 在任务计划程序触发时缩短消息行并中断 FullNames

Send-MailMessage shortens lines in message when triggered by Task Scheduler and breaks FullNames

我找不到原因 电子邮件中的行在任务计划程序触发时被缩短(当脚本从伊势!)。我想将 FullName 传递给电子邮件并将其用作 link 来记录(当路径和文件不包含 spaces 时,link 效果很好)。

如果我使用 "format-list" 而不是 "format-table" 它看起来更好(即使由 Task Scheduler 触发)并且我必须添加参数 "$body = $newdoc | Out-String -Width 255 " 以防止断行 - 但文件名中的 space 仍然会中断 links:

接下来是 FullName 包含 spaces - 我尝试了很多方法(比如 $variable.replace; $var = $var -replace " ","` ", 等等)

#date and time formating
$culture = Get-Culture
$culture.DateTimeFormat.LongTimePattern = 'HH:mm'
$culture.DateTimeFormat.ShortDatePattern = 'dd-MM-yyyy'
Set-Culture $culture

#find files changed during last hour, sort descending
$newdoc = get-childitem -File -Path \ottm09itoms01\OTA-IT_Operators\ -Recurse | ? {$_.LastWriteTime -gt (Get-Date).AddHours(-1)} | sort lastwritetime -Descending | Format-table -Property LastWriteTime, fullname

$body = $newdoc | Out-String
$enc  = New-Object System.Text.utf8encoding
Send-MailMessage -From $sender -To $receiver2 -Subject "Documents updated" -body $body -Encoding $enc -SmtpServer $SMTPserver

经过一些挖掘,我怀疑问题出在您使用 Out-String 时,t运行 根据您未指定的 -width 参数对输出进行分类。引用 the documentation:

-width
Specifies the number of characters in each line of output. Any additional characters are truncated, not wrapped. If you omit this parameter, the width is determined by the characteristics of the host program. The default value for the Windows PowerShell console is 80 (characters).

换句话说,当您 运行 ISE 中的此脚本 Out-String 可能会将宽度设置为 ISE 的缓冲区宽度,但是当任务计划程序 运行s它,它使用默认的 80 个字符宽度。

所以基本上只需将 -width 120(或您选择的值)添加到您的 Out-String,看看是否能解决问题。


要修复因空格而中断的链接,您可能需要使用 -replace 为它们手动生成一些 HTML。类似于:

$body = $body -replace '(\\.*[^\s])','<a href=""></a>'
$body = $body.trim() -replace "`n","<br>`n"

这假定您的所有路径都是 UNC 路径(即以 \ 开头的路径)。然后,您需要在 Send-MailMessage 命令上添加 -BodyAsHtml。这有点混在一起,我相信可能有更好的做事方式,但它 应该 有效。