I want to adjust the code to to test connectivity to a port lets say 3 times. If all 3 fail to then send an email. I presume a counter is my solution but I am at an impass. This is what I have but I know there is a better way! Cheers fellas
### Port Test
$25Port = Test-NetConnection 8.8.8.8 -Port 25 -InformationLevel Quiet
### IF statment to Test the Port
if ($25Port -match "False")
{
if ($25Port -match "False")
{
if ($25Port -match "False")
{
if ($25Port -match "False")
{
$sentemail = Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $Credentials
}
}
}
}
$Fail is equal to 0 at beginning of script $Fail++ enumerates it + 1 for every loop until it gets to 3 . a similar thing is happening in the For loop it is adding 1 to $i until it gets to 3
when ever a variable has an integer in it and you do ++ you increment it + 1.
its like saying
$fail = 0
$Fail = $Fail + 1
I hope I explained that well I came from VB and sometimes my logic is off.
$fail++ is equivalent to $fail = $fail + 1. In other words add 1 to $fail variable (keep track of the failures). If you hit 3 failures, send message.
As far as the for loop, a for loop is an old iteration loop found in majority of programming languages. Someone else might be able to point you to a good article or write-up on it, but in general the syntax is:
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Code for the for-loop’s body goes here.
}
INITIALIZATION - Runs before the for loop is executed, in our example it initialized $i = 0.
CONDITION - After each iteration the condition is checked. If true, the for loop iterates again, if false the for loop is complete
AFTERTHOUGHT - Runs upon completion of each iteration of the loop. In our example, adds 1 to $i.