Pinging Servers with PowerShell

This script can be utilized if you need to ping a list of IP addresses to ensure they are online or if you need to resolve the IPs into FQDNs.

<#
Requirement(s)  : You must populate a servers.txt file with the IP addresses of the servers; one line per IP address.
Purpose		    : This script will attempt to ping the IP addresses and return if the ping was successful or not and also display the hostname if available.
Execution	    : 1) Populate a servers.txt in a staging directory, one line per IP address
                  2) Replace the staging directory with the one within this script within the double quotes
                  3) Within Powershell, navigate to staging directory and execute script


#>


#****Replace this directory with your staging directory, within the double quotes!****#
cd "H:\Code\"

#Reads content of servers.txt and sets it to $Servers variable
$Servers = gc servers.txt

#Sets the timeout of the Ping attempt
$Timeout = 100

#Creates a object for .Net class NetworkInformation with action of Ping
$Ping = New-Object System.Net.NetworkInformation.Ping

#Creates a loop to perform the below steps for each IP address found in $Servers
foreach ($Server in $Servers)
{
	#Attempt to execute below steps
	try 
	{
		#Execute $Ping function from .Net class to IP address and time out at 100 ms
		#Set output to $Response variable
		$Response = $Ping.Send($Server,$Timeout)

		#Response output is multilined, we only need the Status field of the output
		#Set status output to $Reply varaible
		$Reply = $Response.Status

		#Determine FQDN of IP address and set it to $HostName variable
		$HostName = [Net.DNS]::GetHostEntry($Server).HostName
		
		#If/Else statements to determine output based on $Reply variable's content of status
		#If $Reply contains "Timedout" string
		if ($Reply | Select-String "Timedout")
		{	#Displays $Reply (Status), $Server (IP Address), $HostName (FQDN) displays text in Red color
			Write-Host "$Reply $Server $HostName" -ForegroundColor Red		
		}
		
		#If $Reply containts "Success" string
		elseif ($Reply | Select-String "Success")
		{	#Displays $Reply (Status), $Server (IP Address), $HostName (FQDN) displays text in Green color
			Write-Host "$Reply $Server $HostName" -ForegroundColor Green		
		}
		
		#If $Reply contains anything else
		else
		{	#Displays $Reply (Status), $Server (IP Address), $HostName (FQDN) displays text in Yellow color
			Write-Host "$Reply $Server $HostName" -ForegroundColor Yellow		
		}
	}

	#If any error exceptions occur that is not handled within the if/else statements, the below will execute
	catch 
	{
		Write-Host "$Server unreachable!"	-ForegroundColor Red
	}
}

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments