繁体   English   中英

在 powershell 中获取 ping 的结果

[英]Getting results of a ping in powershell

我正在使用 powershell ping IP 地址,我希望能够根据该响应发送 email。 So for example if I ping my IP address and it's working then I want to send an email that says it's on, but if I ping the IP address and I get Request Timed Out then I don't send an email.

我的代码

$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";

正确的纯 Powershell 方式将是这样的

if (Test-Connection -ComputerName 'IPAddress' -Count 1 -Quiet) {
    'Send email'
}

如果我从我的 IP 地址收到回复,我已经设法发送了 email。

我将此代码添加到我的文件中。

$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";    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM