获取powershell中ping的结果

获取powershell中ping的结果,powershell,Powershell,我正在使用powershell连接到平安IP地址,我希望能够基于该响应发送电子邮件。例如,如果我ping我的IP地址并且它工作,那么我想发送一封电子邮件,说它已打开,但是如果我ping我的IP地址并且我得到请求超时,那么我不发送电子邮件 我的代码 $Username = "username"; $Password = "password"; ping ip_address function Send-ToEmail([string]$email){

我正在使用powershell连接到平安IP地址,我希望能够基于该响应发送电子邮件。例如,如果我ping我的IP地址并且它工作,那么我想发送一封电子邮件,说它已打开,但是如果我ping我的IP地址并且我得到
请求超时
,那么我不发送电子邮件

我的代码

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

如果我从我的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";    
}

如果我从我的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";    
}

正确的纯Powershell方式应该是这样的

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

正确的纯Powershell方式应该是这样的

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

您可以使用
测试连接
而不是
ping
。请阅读完整的帮助,包括示例,以了解如何使用它。我将研究它。谢谢您可以使用
测试连接
而不是
ping
。请阅读完整的帮助,包括示例,以了解如何使用它。我将研究它。感谢您不要使用ping(需要解析),我建议您使用Test-connection。我认为您的代码不会工作,因为即使机器无法ping,它也会发送电子邮件。考虑这个输出:<代码>从192.1681.222回复:目标主机不可访问。< /代码>。您的代码在
Reply
上查找匹配项。我建议您不要使用ping(需要解析),而是使用Test-connection。我不认为您的代码可以工作,因为即使计算机无法ping,它也会发送电子邮件。考虑这个输出:<代码>从192.1681.222回复:目标主机不可访问。< /代码>。您的代码在
Reply
上查找匹配项。