首页 > 解决方案 > 如何使用Powershell检查电子邮件是否已发送

问题描述

我目前正在编写一个 Powershell 脚本,它会 ping 服务器,如果无法建立连接,则会向 IT 部门发送电子邮件以手动重新启动服务器。

现在,当 ping 不成功并且对象具有属性值(应该评估为“True”)时,脚本可以成功发送电子邮件,但我无法验证这一点,因为在发送电子邮件时,变量删除本身,因此该属性不再存在。

    $Outlook = New-Object -ComObject Outlook.Application
    $Mail = $Outlook.CreateItem(0)
    $Mail.To = "<recipient>"
    $Mail.Cc = "<some_cc>"

    $Mail.Send()
    # After this line, the variable is deleted!
    if ($Mail.Sent()) 
    # The line which is supposed to work, but evaluates to False everytime

在我可以验证交换之前,如何确保此变量仍然存在?

标签: powershell

解决方案


该变量在 Send 方法之后将无法生存,也不会返回值。您将实际发送操作委托给 Outlook,因此您需要检查 Outlook 应用程序是否有错误(即退回)。

如果不需要通过 Outlook 发送,您可以使用更多选项

try {
    Send-MailMessage -From 'monitoring@example.com' -To 'ITdesk@example.com' -Subject 'test' -Body 'whatever'  -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'mail.example.com' -ErrorAction stop -Port 25
}
catch{
    write-warning "error in sending. $_"
}

请注意,如果您需要经过身份验证的发送,您可以通过 -credential 参数指定保存的凭据。

此处参考: https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-6


推荐阅读