You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell监控日志并发送单封邮件捕获完整错误块?

PowerShell日志监控:合并连续错误块发送单封告警邮件

当然可以实现。你的原脚本每匹配到一行目标字符串就发送一封邮件,导致连续错误行触发多封告警。我们可以通过缓存连续的错误行,直到错误块结束时再发送单封邮件来解决这个问题。

修改后的脚本

# 配置邮件参数
$smtpServer = "x.x.x.x"
$fromAddr = "ALERT@com"
$toAddr = "alert.com"
$alertSubject = "服务器错误块告警"

# 初始化错误块缓存
$errorLines = @()

Get-Content C:\temp\server.log -Wait -Last 0 | ForEach-Object {
    $currentLine = $_
    if ($currentLine -match "ERROR \[STDERR\]") {
        # 将匹配的错误行加入缓存
        $errorLines += $currentLine
    }
    else {
        # 遇到非错误行时,检查缓存是否有内容
        if ($errorLines.Count -gt 0) {
            # 合并缓存的错误行为邮件正文
            $mailBody = $errorLines -join "`n"
            # 发送告警邮件
            Send-MailMessage -SmtpServer $smtpServer -From $fromAddr -To $toAddr -Subject $alertSubject -Body $mailBody
            # 清空缓存,准备捕获下一个错误块
            $errorLines = @()
        }
    }
}

# 脚本停止时,检查是否有未发送的剩余错误块
if ($errorLines.Count -gt 0) {
    $mailBody = $errorLines -join "`n"
    Send-MailMessage -SmtpServer $smtpServer -From $fromAddr -To $toAddr -Subject $alertSubject -Body $mailBody
}

脚本逻辑说明

  1. 缓存错误行:用数组$errorLines存储连续匹配ERROR [STDERR]的行,直到遇到非匹配行。
  2. 触发邮件发送:当检测到非错误行时,说明当前错误块已结束,将缓存的所有错误行合并为邮件正文,发送单封告警后清空缓存。
  3. 收尾处理:脚本停止运行时,检查缓存中是否有未发送的错误块,避免遗漏最后一段错误日志。

扩展优化(可选)

如果你的错误块之间可能夹杂少量非错误行(比如空行),可以添加超时逻辑:当超过指定秒数没有新的错误行时,自动发送当前缓存的错误块。示例如下:

$errorLines = @()
$lastErrorTime = Get-Date
$timeoutSeconds = 5

Get-Content C:\temp\server.log -Wait -Last 0 | ForEach-Object {
    $currentLine = $_
    if ($currentLine -match "ERROR \[STDERR\]") {
        $errorLines += $currentLine
        $lastErrorTime = Get-Date
    }
    else {
        $timeSinceLastError = (Get-Date) - $lastErrorTime
        if ($errorLines.Count -gt 0 -and $timeSinceLastError.TotalSeconds -ge $timeoutSeconds) {
            $mailBody = $errorLines -join "`n"
            Send-MailMessage -SmtpServer $smtpServer -From $fromAddr -To $toAddr -Subject $alertSubject -Body $mailBody
            $errorLines = @()
        }
    }
}

内容的提问来源于stack exchange,提问作者Donald Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:42:58