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

如何修改PowerShell测速脚本 实现速率低于阈值时触发邮件告警

PowerShell 局域网测速告警逻辑实现方案

核心实现步骤

1. 捕获并解析speedtest.exe输出的速率数值

优先推荐使用官方speedtest cli的JSON输出格式,解析稳定性更高:

# 调用speedtest.exe,指定JSON格式输出,可添加--server-id参数指定局域网测速节点
$speedtestResult = & "你的speedtest.exe完整路径" --accept-license --accept-gdpr --format=json | ConvertFrom-Json

# 官方默认返回带宽单位为字节/秒,转换为Mbps
$downloadSpeed = [math]::Round($speedtestResult.download.bandwidth * 8 / 1MB, 2)
$uploadSpeed = [math]::Round($speedtestResult.upload.bandwidth * 8 / 1MB, 2)

如果你的speedtest工具不支持JSON输出,用正则匹配文本输出也可以:

# 捕获文本输出
$speedtestOutput = & "你的speedtest.exe完整路径"
# 正则匹配下载、上传速率数值
$downloadMatch = $speedtestOutput | Select-String -Pattern 'Download:\s*([\d.]+)\s*Mbps'
$uploadMatch = $speedtestOutput | Select-String -Pattern 'Upload:\s*([\d.]+)\s*Mbps'

# 转换为数值类型,保留两位小数
$downloadSpeed = [math]::Round([double]$downloadMatch.Matches.Groups[1].Value, 2)
$uploadSpeed = [math]::Round([double]$uploadMatch.Matches.Groups[1].Value, 2)

2. 添加阈值判断与告警触发逻辑

按你要求的下载低于50Mbps且上传低于5Mbps时才发告警的规则编写条件判断,把你原有发邮件的逻辑放到判断分支内即可:

# 配置阈值
$downloadThreshold = 50.0
$uploadThreshold = 5.0

# 条件判断
if ($downloadSpeed -lt $downloadThreshold -and $uploadSpeed -lt $uploadThreshold) {
    # 此处替换为你原有SMTP发邮件的逻辑,示例如下
    $mailParams = @{
        SmtpServer = "你的SMTP服务器地址"
        Port = 你的SMTP端口,比如465
        UseSsl = $true
        Credential = New-Object System.Management.Automation.PSCredential ("发件人邮箱地址", ("发件人邮箱授权码" | ConvertTo-SecureString -AsPlainText -Force))
        From = "发件人邮箱地址"
        To = "收件人邮箱地址"
        Subject = "局域网测速告警通知"
        Body = "本次测速结果未达标:
下载速率:$downloadSpeed Mbps(阈值:$downloadThreshold Mbps)
上传速率:$uploadSpeed Mbps(阈值:$uploadThreshold Mbps)"
    }
    Send-MailMessage @mailParams
}

注意事项

  • 如果需要只要下载或上传任意一项不达标就触发告警,把判断条件里的-and改为-or即可
  • 正式使用前建议先打印$downloadSpeed和$uploadSpeed的数值,确认解析结果正确,避免匹配错误导致判断失效
  • 如果你的speedtest工具输出的速率单位不是Mbps,需要先做单位转换再和阈值比较

内容的提问来源于stack exchange,提问作者יגאל אקרמן

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:54:03