控制台输出到 Powershell 中的电子邮件

Console output to email in Powershell

我正在为每月维护过程编写一个 powershell 脚本。为了跟踪它,我使用了一个 try catch 块,它会在成功或失败时发送一封电子邮件。为此,我使用 smtp。我想知道如何将控制台输出写入电子邮件。如果您有任何建议,请告诉我。入门有困难。

提前谢谢你。

这是我最近尝试过但没有用的方法:

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();

}

问:什么"Didn't work"?

建议:

1) 编写一个故意触发错误的示例脚本

2) 确保您已成功捕获所需的错误文本(您应该能够从 $_ 获取它,就像您正在做的那样)

3) 确保您的电子邮件参数正确

4) 分而治之:首先是 Powershell 语法,然后是电子邮件连接。

我的预感是您需要调试电子邮件连接。

例如:

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();

}