March 31 2014

Powershell script to ping and check ports 80 & 443

A while back I created a very simple PS script for pinging a list of servers (http://blog.danovich.com.au/2009/06/10/nifty-powershell-script-to-ping-multiple-servers/). I’ve make a few changes to it recently including a couple of columns to check for TCP port 80 & 443 connectivity. Expect an output to Excel similar to this:

Ping script

 

 
$erroractionpreference = "SilentlyContinue"
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "Ping Status"
$c.Cells.Item(1,3) = "IP Address"
$c.Cells.Item(1,4) = "Port 80"
$c.Cells.Item(1,5) = "Port 443"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$d.EntireColumn.AutoFit($True)
$intRow = 2
$colComputers = get-content C:Tempmachinelist.txt
foreach ($strComputer in $colComputers)
{
$c.Cells.Item($intRow, 1) = $strComputer.ToUpper()
# This is the key part
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strComputer)
if ($Reply.status -eq "Success")
{
$c.Cells.Item($intRow, 2) = "Resolved & active"
$c.Cells.Item($intRow, 3) = $Reply.Address.ToString()
}
elseif ($Reply.status -eq "TimedOut")
{
$c.Cells.Item($intRow, 2) = "Resolved host but timed out"
$c.Cells.Item($intRow, 3) = $Reply.Address.ToString()
}
else
{
$c.Cells.Item($intRow, 2) = "Unable to resolve"
}
$socket80 = new-object Net.Sockets.TcpClient
$socket80.Connect($strComputer, 80)
if ($socket80.Connected) {
$c.Cells.Item($intRow, 4) = "Open"
$socket80.Close()
}
else 
{
$c.Cells.Item($intRow, 4) = "Not Open"
}
$socket443 = new-object Net.Sockets.TcpClient
$socket443.Connect($strComputer, 443)
if ($socket443.Connected) {
$c.Cells.Item($intRow, 5) = "Open"
$socket443.Close()
}
else 
{
$c.Cells.Item($intRow, 5) = "Not Open"
}
$Reply = ""
$intRow = $intRow + 1
}
$d.EntireColumn.AutoFit()

 

 

 



----------------------------------------------------------------------------
I use a maximum of one Google Ad per post to help offset some of my blog hosting costs.

----------------------------------------------------------------------------


Tags: , , , , ,

Posted March 31, 2014 by danovich in category "Powershell", "Scripting

2 COMMENTS :

  1. Pingback: NeWay Technologies – Weekly Newsletter #89 – April 3, 2014 | NeWay

  2. Pingback: NeWay Technologies – Weekly Newsletter #89 – April 4, 2014 | NeWay

Leave a Reply