0

I have script:

$servers = "server01", "s02", "s03"

foreach ($server in $servers) {

$server = (New-Object System.Net.NetworkInformation.Ping).send($servers)
if ($server.Status -eq "Success") {
Write-Host "$server is OK"
}
}

Error message:

An exception occured during a Ping request.

I need to ping each server in $servers array and display status. I think, that Foreach statement is not properly used, but I'm unable to find out where is the problem. Thank you for your advice

1 Answer 1

3

You should not be modifying the value of $server within the foreach loop. Declare a new variable (e.g. $result). Also, Ping.Send takes the individual server name, not an array of server names as an argument. The following code should work.

Finally, you will need to trap the PingException that will be thrown if the host is unreachable, or your script will print out a big red error along with the expected results.

$servers = "server1", "server2"

foreach ($server in $servers) {
   & {
       trap [System.Net.NetworkInformation.PingException] { continue; }
       $result = (New-Object System.Net.NetworkInformation.Ping).send($server)
       if ($result.Status -eq "Success") {
         Write-Host "$server is OK"
       }
       else {
         Write-Host "$server is NOT OK"
       }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.