Reputation: 199
I'm using powershell to ping an IP address and I would like to be able to send an email based on that response. 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.
My code
$Username = "username";
$Password = "password";
ping ip_address
function Send-ToEmail([string]$email){
$message = new-object Net.Mail.MailMessage;
$message.From = "[email protected]";
$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 "[email protected]";
Upvotes: 0
Views: 2014
Reputation: 5252
The proper pure Powershell way would be something like this
if (Test-Connection -ComputerName 'IPAddress' -Count 1 -Quiet) {
'Send email'
}
Upvotes: 2
Reputation: 199
I've managed to send an email if I get a response back from my IP address.
I added this code to my file.
$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 "[email protected]" -content "The computer is on";
}
Upvotes: 0