我正在使用powershell来ping一个IP地址,我希望能够根据该响应发送一封电子邮件。例如,如果我ping我的IP地址,它正在工作,那么我想发送一封电子邮件,说明它已打开,但如果我ping该IP地址,并获得Request Timed Out,则我不会发送电子邮件。
我的代码
$Username = "username";
$Password = "password";
ping ip_address
function Send-ToEmail([string]$email){
$message = new-object Net.Mail.MailMessage;
$message.From = "from@test.com";
$message.To.Add($email);
$message.Subject = "subject text here...";
$message.Body = "body text here...";
$smtp = new-object Net.Mail.SmtpClient("smtp.mailtrap.io", "2525");
$smtp.EnableSSL = $false;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message);
write-host "Mail Sent" ;
}
Send-ToEmail -email "reciever@test.com";发布于 2020-07-21 17:03:48
正确的纯Powershell方式应该是这样的
if (Test-Connection -ComputerName 'IPAddress' -Count 1 -Quiet) {
'Send email'
}发布于 2020-07-21 15:58:03
我已经设法发送了一封电子邮件,如果我得到一个回应,从我的IP地址。
我将此代码添加到我的文件中。
$ping = ping ip_address -n 1 | Where-Object {$_ -match "Reply" -or $_ -match "Request timed out" -or $_ -match "Destination host unreachable"}
If($ping -match "Reply")
{
Send-ToEmail -email "reciever@test.com" -content "The computer is on";
}https://stackoverflow.com/questions/63009418
复制相似问题