Telnet isn't used too often anymore but we have PowerShell to do some simple port testing that telnet once did.

You know what grinds my gears? Telnet is no longer a default option in Windows. Gone are the days where one could easily test an open TCP port by doing telnet HOSTNAME PORTNAME.

Good ol' telnet. Sure, all activity could easily be seen across the wire but it was sure convenient. What's an admin to do?

Well, where should an admin look to nearly every time? Powershell, of course! Technically, you could get it added via adding a feature but we're not going to go there.

Using the .NET TcpClient class we can instruct PowerShell to use this to create an object to open up a temporary connection against a remote computer.

Based on if an error is thrown or not lets us know if the TCP port is open or not. In a nutshell, this function initiates the Connect() method on the TcpClient object on a remote computer against a TCP port. If the Connect() method does not throw an error the $status variable is set to Open. If it does throw an error, it will be caught and set to Closed/Filtered. Finally, a custom object will be created with all the parameters necessary and put onto the pipeline.

## This script needs v3 because we use the PSCustomObject type accelerator as an output to the function
#Requires -version 3

function Test-TcpPort ($ComputerName,$TcpPort) {
    try {
        ## Create the TcpClient object and initiate a Connect method
        $socket = new-object Net.Sockets.TcpClient
        $socket.Connect($ComputerName, $TcpPort)
        ## The script will only get here if an error is not thrown by the above method
        $status = "Open"
        ## Properly close the TCP connection once we're done
        $socket.Close()
    } catch {
        $status = 'Closed/Filtered'
    } finally {
        $obj = [PSCustomObject]@{
            ComputerName = $ComputerName
            TcpPort = $TcpPort
            Status = $status
        }
        $obj
    }
}

## Usage
$ComputerName = '192.168.10.30'
$TcpPort = '88'

Test-TcpPort $ComputerName $TcpPort

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!