Checking connectivity to Ports using Windows PowerShell

Today I had an agent with a heartbeat failure and in the Operations Manager Event Log there were 21006 error’s indicating that it couldn’t contact the Management Server. Firstly I wanted the check if this agent could contact the management server on port 5723. Unfortunately there were no telnet, portqry or network monitoring type tools or applications on this box. Naturally, it got me thinking about PowerShell.

So here’s a little function which you can use to test connectivity to any port, not just the SCOM agent one.

Usage:
Test-Port ServerName 5723

 

Function Test-Port
{
Param (
[Parameter(Position=1, Mandatory=$true)] [string]$Computer,
[Parameter(Position=2, Mandatory=$true)] [int]$Port
)

# Use Net.Sockets.TcpClient to query the TCP port
$Socket = New-Object Net.Sockets.TcpClient

# Suppress error messages
$ErrorActionPreference = ‘SilentlyContinue’

# Try the connection
$Socket.Connect($Computer, $Port)

# Make error messages visible again
$ErrorActionPreference = ‘Continue’

# Are we connected?
if ($Socket.Connected) {

“${Computer}: Port $Port is open”
$Socket.Close()

} else {

“${Computer}: Port $Port is closed or filtered”

}

# Set the Variable to Null
$Socket = $null
}

 

Disclaimer: I did find a script on the web that contained a lot of this code…my apologies to the original author (whoever you are), I cannot remember where I found it.

 

 
Comments

Very useful. Thank a lot

Leave a Reply