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

如何过滤PowerShell测试连接的失败结果并自动发送邮件?

解决Test-Connection失败机器过滤与邮件告警问题

核心思路

Test-Connection默认不会将失败的机器信息存入结果对象,需要通过捕获错误的方式收集失败目标,再结合PowerShell的邮件命令实现自动化告警。

完整脚本示例

# 1. 读取目标机器列表
$computers = Get-Content 'C:\xxxxx\xxxxx.txt'
# 2. 初始化空数组存储失败的机器
$failedComputers = @()

# 3. 遍历每台机器测试连接
foreach ($computer in $computers) {
    try {
        # 用-ErrorAction Stop触发异常,捕获连接失败的情况
        Test-Connection -ComputerName $computer -Count 1 -ErrorAction Stop | Out-Null
    }
    catch {
        # 将失败的机器名存入数组
        $failedComputers += $computer
    }
}

# 4. 若存在失败机器,发送告警邮件
if ($failedComputers.Count -gt 0) {
    # 生成易读的邮件内容
    $mailBody = @"
以下远程机器连接测试失败:
$(($failedComputers | ForEach-Object { "- $_" }) -join "`n")
"@

    # 发送邮件(根据实际环境修改参数)
    Send-MailMessage -From "connection-monitor@yourdomain.com" `
                     -To "admin@yourdomain.com" `
                     -Subject "远程机器连接失败告警" `
                     -Body $mailBody `
                     -SmtpServer "smtp.yourdomain.com" `
                     -Port 587 `
                     -UseSsl `
                     -Credential (Get-Credential)
}

关键细节说明

  • 捕获失败机器:通过try/catch配合-ErrorAction Stop,让连接失败时触发异常,从而将失败机器名存入数组,避免默认的错误输出干扰结果收集。
  • 邮件内容格式化:使用Here-String生成结构化的邮件正文,将失败机器以列表形式展示,便于查看。
  • 邮件参数调整:根据你的SMTP服务器配置修改发件人、收件人、服务器地址等参数,若无需SSL或认证,可移除-UseSsl和-Credential选项。

高效优化方案(PowerShell 7+适用)

如果使用PowerShell 7及以上版本,可利用异步批量测试提升效率:

$computers = Get-Content 'C:\xxxxx\xxxxx.txt'
# 批量异步测试,返回包含连接状态的结果对象
$results = Test-Connection -ComputerName $computers -Count 1 -AsJob | Receive-Job -Wait -AutoRemoveJob
# 直接过滤出连接失败的机器
$failedComputers = $results | Where-Object { $_.StatusCode -ne 0 } | Select-Object -ExpandProperty ComputerName

# 后续邮件发送逻辑与上述示例一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:16:14