PING a Machine from Powershell

Hi Folks ,

If you work in an environment where you need to restart Servers in a certain order. One way of validating that a server is back on-line is to ping it . Well how can you do that from Powershell ?

Well by using the .net framework of course . Lets write some code to ping the Server lets say for example that you reboot the server with the wmi class Win32_OperatingSystem like so:

 

  1. Reboot Server

$server = gwmi Win32_operatingsystem
$server.reboot()

What you want to do next, especially if you need to keep track of the status of the server online or offiline, is ping the server and based on the status either continue or wait till the server comes back up .

This comes in handy if say you have an application Server and a Database Server . The requirement is to have the Database Server up before the Applications server so the Apps can connect to SQL and there will be no problems . So after rebooting the SQL Server you would setup a ping and some loops as so .

# Create a new instance of ping
$ping = new-object System.Net.Networkinformation.Ping
#Show message that the Server is still reachable
write-host "YourServerName is Still reachable" -NoNewLine -ForegroundColor "Green"

# This piece waits till the Server is no longer Reachable
do{$result = $ping.send("ServerName");write-host "." -NoNewline -ForegroundColor "Green"}
Until($result.status -ne "Success")
Write-host ""
write-host "ServerName is not reachable" -ForegroundColor "Red"

Now we are going to write the code that waits for the Server to Come up .

#This piece waits for the Server to come back online .
do{$result = $ping.send("ServerName");write-host "." -NoNewLine -ForegroundColor "Red"}
until ($result.status -eq "Success")

So to recap we used some do …until loops to wait for the Server to come back online . This is a good way to control the process . If you know any other ways to properly control scripts when rebooting Servers please write in the comments . Or if you like this technique please let me know 🙂

Thanks and I hope this helps your scripting needs .

Chris

Advertisements