PowerShell批量ping检测脚本运行后邮件正文输出重复如何解决
PowerShell批量ping脚本重复输出问题修复方案
问题根因
- 输出文件使用
-Append参数追加写入,没有每次运行前清空旧内容 $body变量使用+=赋值,会累加历史运行的变量残留值Clear-Content用法错误,既没有实现清空文件的效果,也不能正确给$body赋值
修改后的完整脚本
cls # 初始化body变量,避免历史值残留 $body = "" $ip = Get-Content -Path 'D:\ping text.txt' # 每次运行前先清空旧结果文件 if (Test-Path "D:\result.html") { Remove-Item "D:\result.html" -Force } foreach ( $ip1 in $ip ) { $ip2 = ping $ip1 if ( $ip2 -imatch "(100% loss)") { Write-Host "$ip1 is failed" -ForegroundColor Red $output="$ip1 is failed" } elseif ($ip2 -imatch "Ping request could not find host") { Write-Host "$ip1 could not find host" -ForegroundColor Red $output = "$ip1 could not find host" } else { Write-Host "$ip1 is success" -ForegroundColor Green $output="$ip1 is success" } $output | Out-File "D:\result.html" -Append } # 直接读取本次运行结果赋值,不用累加 $body = [System.IO.File]::ReadAllText("D:\result.html") Send-MailMessage -From 'X' -To 'Y' -Subject 'Sending the Attachment' -Body $body -Attachments D:\result.html -Priority High -SmtpServer 'webmail.wipro.com' -Port 587
核心修改说明
- 脚本开头初始化
$body为空字符串,避免上一次运行的变量值残留 - 处理IP前先删除旧的结果文件,保证本次写入的内容不会和历史内容叠加
- 读取结果赋值给
$body时直接用=赋值,移除错误的+=和Clear-Content写法
内容的提问来源于stack exchange,提问作者Dark
相关产品推荐
相关产品推荐

