我正在使用Send-MailMessage
函数通过电子邮件发送备份的日志文件。我编辑了PowerShell配置文件,因此会自动创建脚本文件。如果备份遇到错误,则调用SendMailErr函数。
这有效,但我想将脚本文件和日志文件添加为附件(如果存在)。如果它们不存在,我想改变电子邮件的正文,说“成绩单不存在等。”
我的笨拙代码处于当前状态
# Mail Settings
$to = "first.lastname@unisa.edu.au"
$from = "$env:ComputerName@unisa.edu.au"
$Smtp = "mx-out.company.edu.au"
$body = "Please review attached log file $seperator See $blog for WBAdmin Log"
$attachments = "$logfile","$trans" | Where-Object {Test-Path $_ }
#Transcript File
$trans = Get-ChildItem $bLog `
-filter "$env:computername-PSTranscript-$(get-date -format ddMMyyyy).log"
-Name
function SendMailErr {
$MessageParameters = @{
From = $from
To = $to
Subject = "ALERT: Backup Failed for $env:ComputerName.$env:USERDNSDOMAIN `
- $((Get-Date).ToShortDateString())"
Body = $body
SmtpServer = $Smtp
Priority = "High"
Attachments = $attachments
}
Send-MailMessage @MessageParameters
Exit
}
非常感谢任何建议。
谢谢。
无肢
答案 0 :(得分:1)
我通常接近这样:
从$ body的空数组开始。当您遇到要向主体添加文本的条件时,请使用+ =添加这些字符串。在发送之前,通过out-string运行它以将其转换为字符串并添加换行符。
$body = @()
if (test-path $logfile){$body += "Log file $logfile attached"}
else {$body += "Log file $logfile was not found"}
if (test-path $trans){$body += "Transcript file $trans attached"}
else {$body += "Transcript file $trans was not found"}
$body = $body | out-string