【问题标题】:In PowerShell, how to I send mail and enumerate in email body list of discovered errors在 PowerShell 中,如何发送邮件并在电子邮件正文列表中枚举发现的错误
【发布时间】:2012-01-13 20:08:46
【问题描述】:

我的 PowerShell 脚本中有以下代码 sn-p...

  • 遍历服务器列表
  • 是否在每台服务器的错误日志中选择字符串不匹配
  • 如果错误日志错误则标记服务器,如果错误日志正常则返回 OK

我还想做的是发送一封电子邮件报告,在列表中列举每个发现的错误日志,并列出所有错误日志正常的服务器。电子邮件正文中的内容如下:

以下服务器有错误日志:

  • 服务器3
  • 服务器6
  • 服务器 14

以下服务器都可以:

  • 服务器 1
  • 服务器2
  • 服务器5

这是我的代码 sn-p:

$Servers = Get-Content $ServerLst
ForEach ($Server in $Servers)
{
   $ErrorLog = Get-ChildItem -Path \\$Server\$LOG_PATH -Include Error.log -Recurse | Select-String -notmatch $SEARCH_STR
   If ($ErrorLog)
   {
    Write-Host "Bad Error Log found at $Server!"
   }
   Else
   {
    Write-Host "Error log is OK."           
   }
}

我猜我需要一个 Send-Mail 函数,我可以在其中传递带有错误日志等的服务器名称。但是,我不太确定如何解决这个问题。

我们将不胜感激任何伟大的想法。谢谢!

【问题讨论】:

    标签: powershell sendmail


    【解决方案1】:

    如果您使用 Powershell V1,请使用 Powershell Cookbook 中的 this function 发送邮件。在 Powershell V2 中,您可以使用 Send-MailMessage 发送邮件。

    $Servers = Get-Content $ServerLst
    $Bad = "The following servers have bad error logs:`n`n"
    $OK = "`nThe following servers are OK:`n`n"
    ForEach ($Server in $Servers)
    {
       $ErrorLog = Get-ChildItem -Path \\$Server\$LOG_PATH -Include Error.log -Recurse | Select-String -notmatch $SEARCH_STR
       If ($ErrorLog)
       {
        $Bad += "`t - $Server`n"
       }
       Else
       {
        $OK += "`t - $Server`n"           
       }
    }
    Send-MailMessage -Body "$Bad $OK" -Subject "Bad Logs" -SmtpServer $servername -To $to -From $from  
    

    备注: smtpserver 参数在 Powershell 食谱函数中称为 smtphost。

    【讨论】:

    • 谢谢!这看起来像一个干净的方法。等我回去工作的时候试试看。
    • 嗨 Jon Z,只是为了跟进...我已经尝试了您的解决方案,到目前为止效果很好!再次感谢!!
    • 另一个问题。我想更进一步,指定错误日志错误的服务器数量和正常的服务器数量。因此,$Bad 类似于“以下 n 个具有错误日志的服务器:”。 $OK 将是..“以下 n 个服务器都可以:”。我该怎么做?我想我需要进行计数,但不确定在哪里进行计数。
    【解决方案2】:

    你需要自己制作这个函数,但这里有一些伪代码:

    Function SendMail
    {
        Param(...your params here)
    
        ...send the mail...
    
    
    }
    
    <...
    
    Your code to check all your servers
    
    You need to save your errors or issues to an array or hashtable.  
    I'll assume you use a 2-field array called $ErrArray
    
    ...>
    
    # Now at the end you build a string for the body of the email to incorporate your errors
    
    $StrBody = "Bad Error Log Report`n`n"
    
    $ErrArray | ForEach-Object {$StrBody = $Strbody + "`n$($_[0]) server had an issue: $($_[1])`n"}
    
    SendMail $EmailTo $EmailSubject $StrBody
    

    所以细分:

    • 制作邮件功能
    • 将分析结果保存到数组或哈希表中
    • 遍历您的结果对象并将每个结果记录附加到您的电子邮件字符串中
    • 调用邮件函数

    【讨论】:

    • 您好 JNK,感谢您的反馈!我在想你上面描述的几乎完全相同的事情。只是想得到专家的意见。我会试试你的方法,稍后再回帖...
    • 我在一些较大的脚本中使用了它,当事情处理不正确并且效果很好时,我会发送异常报告。您还应该确保对日志文件使用适当的错误捕获,因为电子邮件过程可能(并且经常会)由于脚本之外的问题而失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2015-12-24
    • 1970-01-01
    • 2012-09-20
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多