PowerShell Telnet as a Telnet Replacement

Adam Bertram

Adam Bertram

Read more posts by this author.

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
    } catch {
        $status = 'Closed/Filtered'
    } finally {
        $obj = [PSCustomObject]@{
            ComputerName = $ComputerName
            TcpPort = $TcpPort
            Status = $status

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

Test-TcpPort $ComputerName $TcpPort

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!