情境,每5分钟检查主机群,当某主机失去连线时,发送MAIL通知 admin@abc.com
1.建立 gogogo.cmd 内容如下:
powershell -file d:\PingTest.ps1
2.将 gogogo.cmd,加到工作排程器,每5分钟(可自订)执行一次.
3.建立 D:\PingTest.ps1 ,内容如下
# 定义欲监测之主机,Hostname或IP$servers = "AP01","192.168.0.1","sql1","10.10.1.76"#flush /register dns / test connect serversForeach($s in $servers){ if(!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet)) { "Problem connecting to $s" "Flushing DNS" ipconfig /flushdns | out-null "Registering DNS" ipconfig /registerdns | out-null "doing a NSLookup for $s" nslookup $s #when re-ping fail, Send mail "Re-pinging $s" if(!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet)) {"Problem still exists in connecting to $s" #Mail content $Emailbody=@" <span style="font-family: 微软正黑体;"><H1>您好,主机 <font color=red>$s</font> 已失联,请查看情况,谢谢</H1></span>"@#SMTP sender $anonUser = "Alarm@abc.com" $anonPass = ConvertTo-SecureString "89OP:./}+" -AsPlainText -Force #Send mail Send-MailMessage -To "admin@abc.com" -Subject "【警告】您的主机'$s'异常!" -Bodyashtml $Emailbody -From "Alarm@abc.com" -SmtpServer "ssl.abc.com" -Encoding ([System.Text.Encoding]::UTF8) } ELSE {"Resolved problem connecting to $s"} #end if } # end if} # end foreach
注意事项:
请确认执行工作排程的帐户及电脑,有权限发送EMAIL(有的SMTP有验证及转发限制)
请自行修改 寄件/收件人/SMTP主机/$servers值
参考:
https://blogs.technet.microsoft.com/heyscriptingguy/2012/02/24/use-powershell-to-test-connectivity-on-remote-servers/