I am using a Send-MailMessage function to email the log files of a backup. I have edited the PowerShell profile so a transcript file is automatically created. If the backup encounters an error the SendMailErr function is called.
This works but I would like to add the transcript file and log file as an attachment (if they exist). If they don’t exist I would like to change the body of the email to say “Transcript does not exist etc.”
My clumsy code in it’s current state
# 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
}
Any advice would be greatly appreciated.
Thank you.
Amelia
I usually approach that like this:
Start with an empty array for $body. As you encounter conditions that you want to add text about to the body, add those strings using +=. Before you send it, run it through out-string to convert it to a string and add newlines.