I am writing a powershell script for a monthly maintenance process. In order to track it I am using a try catch block that will send an email when it succeeds or fails. To do this I am using smtp. I am wondering how to write the console output to the email. Please let me know if you have any suggestions. Having trouble getting started.
Thank you in advance.
This is what I recently tried but it didn't work:
catch {
$smtpServer = "example"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "example"
$msg.To.Add("example")
$msg.Subject = "MONTHLY MAINTENANCE FAILED!"
$msg.Body= Write-Error ("Monthly maintenance failed! Please investigate." + $_)
$smtp.Send($msg)
$msg.Dispose();
}
Q: What "Didn't work"?
SUGGESTION:
1) Write a sample script that deliberately triggers the error
2) Make sure you're successfully capturing the error text you want (you should be able to get it from $_
, like you're doing)
3) Make sure your e-mail parameters are correct
4) Divide and conquer: Powershell syntax first, E-Mail connectivity after.
My hunch is you'll need to debug your e-mail connectivity.
For example:
Try {
1/0 # throw "divide by zero"
}
Catch {
$errmsg = "Monthly maintenance failed! Please investigate." + $_
Write-Console $errmsg
$smtpServer = "example"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "example"
$msg.To.Add("example")
$msg.Subject = "MONTHLY MAINTENANCE FAILED!"
$msg.Body= $errmsg
$smtp.Send($msg)
$msg.Dispose();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.