PowerShell Alternative of Telnet Command

Enable Telnet Command in PowerShell

If you are a Windows System Administrator, you will surely know the importance of Telnet command in your day-to-day life. As you, know that all version of Windows (starting from Vista and above) comes with Telnet client feature disabled by default. If you want to test the connectivity or reachability to some computer, you need to enable the Telnet-Client Windows feature or you will look for some alternative command to Telnet.

The syntax of Telnet is fairly simple as shown below:

Telnet 192.168.0.2 80

Every version of Windows now comes with PowerShell installed out of the box. Today I am going to show you how to enable Telnet in Windows PowerShell. We will create a PowerShell module that will work exactly like traditional Telnet command.

Launch the PowerShell console and type the following command:

New-Object System.Net.Sockets.TcpClient("192.168.0.2", 80)

In the above command, Replace 192.168.0.2 with the IP of server (can be a hostname or domain-name like techtutsonline.com) you want to test connectivity and 80 with the Port number.

Take a look at Connected : True property.

  • True means the connection to server is successful.
  • False means your PC cannot connect to server on specified port.

The above command shows you if destination server is listening of specific port or not.

If you want to be able to use Telnet command in PowerShell console exactly as you do in cmd.exe (command prompt), keep on reading the remaining article.

Creating Telnet PowerShell Module

If you cannot remember long commands or you do not like the above command, you can create a PowerShell module.

To Create a Telnet PowerShell module, follow these steps:

  • Launch Windows PowerShell console with administrator privilege.
  • Run the following command:
New-Item -ItemType File -Path "$env:UserProfile\documents\WindowsPowerShell\Modules\Telnet\Telnet.psm1" -Force

Above command will create a file at predefined location.

  • Run the following command to open the newly created module file with Windows PowerShell ISE:
ise "$env:UserProfile\documents\WindowsPowerShell\Modules\Telnet\Telnet.psm1"
  • Now copy the following code to PowerShell ISE editor and save it.
<#
.Synopsis
Tests the connectivity between two computers on a TCP Port

.Description
The Telnet command tests the connectivity between two computers on a TCP Port. By running this command, you can determine if specific service is running on Server.

.Parameter <ComputerName>
This is a required parameter where you need to specify a computer name which can be localhost or a remote computer

.Parameter <Port>
This is a required parameter where you need to specify a TCP port you want to test connection on.

.Parameter <Timeout>
This is an optional parameter where you can specify the timeout in milli-seconds. Default timeout is 10000ms (10 seconds)

.Example
Telnet -ComputerName DC1 -Port 3389
This command reports if DC1 can be connected on port 3389 which is default port for Remote Desktop Protocol (RDP). By simply running this command, you can check if Remote Desktop is enabled on computer DC1.

.Example
Telnet WebServer 80
This command tells you if WebServer is reachable on Port 80 which is default port for HTTP.

.Example
Get-Content C:\Computers.txt | Telnet -Port 80
This command will take all the computernames from a text file and pipe each computername to Telnet Cmdlet to report if all the computers are accessible on Port 80.
#>
Function Telnet{

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias ('HostName','cn','Host','Computer')]
        [String]$ComputerName='localhost',
        [Parameter(Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
        [int32]$Port,
         [int32] $Timeout = 10000
    )

    Begin {}

    Process {
    foreach($Computer in $ComputerName) {
    Try {
          $tcp = New-Object System.Net.Sockets.TcpClient
          $connection = $tcp.BeginConnect($Computer, $Port, $null, $null)
          $connection.AsyncWaitHandle.WaitOne($timeout,$false)  | Out-Null 
          if($tcp.Connected -eq $true) {
          Write-Host  "Successfully connected to Host: `"$Computer`" on Port: `"$Port`"" -ForegroundColor Green
      }
      else {
        Write-Host "Could not connect to Host: `"$Computer `" on Port: `"$Port`"" -ForegroundColor Red
      }
    }
    
    Catch {
            Write-Host "Unknown Error" -ForegroundColor Red
          }

       }
    
    }
    End {}
}
  • At the end of all the steps, your PowerShell module should be available at the location as shown in image below:

PowerShell Module

That’s it! Your Telnet module is ready for PowerShell. Use can start using it as traditional telnet command

  • Close the existing PowerShell console and open a new console. Type the following command:
Get-Help Telnet -Full

Below is the snapshot of Get-Help Telnet -Full command:

NAME
    Telnet

SYNOPSIS
    Tests the connectivity between two computers on a TCP Port


SYNTAX
    Telnet [-ComputerName] <String> [-Port] <Int32> [[-Timeout] <Int32>] [<CommonParameters>]


DESCRIPTION
    The Telnet command tests the connectivity between two computers on a TCP Port. By running this command, you can determine if specific service is running on
    Server.


PARAMETERS
    -ComputerName <String>

        Required?                    true
        Position?                    1
        Default value                localhost
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false

    -Port <Int32>

        Required?                    true
        Position?                    2
        Default value                0
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false

    -Timeout <Int32>

        Required?                    false
        Position?                    3
        Default value                10000
        Accept pipeline input?       false
        Accept wildcard characters?  false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).

INPUTS

OUTPUTS

    -------------------------- EXAMPLE 1 --------------------------

    PS C:\>Telnet -ComputerName DC1 -Port 3389

    This command reports if DC1 can be connected on port 3389 which is default port for Remote Desktop Protocol (RDP). By simply running this command, you can check
    if Remote Desktop is enabled on computer DC1.


    -------------------------- EXAMPLE 2 --------------------------

    PS C:\>Telnet WebServer 80

    This command tells you if WebServer is reachable on Port 80 which is default port for HTTP.


    -------------------------- EXAMPLE 3 --------------------------

    PS C:\>Get-Content C:\Computers.txt | Telnet -Port 80

    This command will take all the computernames from a text file and pipe each computername to Telnet Cmdlet to report if all the computers are accessible on Port
    80.

RELATED LINKS

Look! You just created a Windows PowerShell module that will feel and behave exactly like regular cmdlets. You can use parameters like -ComputerName, -Port, -Credential, -Verbose, -ErrorAction etc. which is awesome.

Using Telnet Cmdlet

Now, its time to use our newly created Telnet Module. As shown in examples of cmdlet, you can use the Telnet module in 3 different ways.

First Way:

Telnet -ComputerName techtutsonline.com -Port 80
Successfully connected to techtutsonline.com on Port: 80

Second Way:

Telnet techtutsonline.com 80
Successfully connected to techtutsonline.com on Port: 80

Third Way:

Get-Content D:\Servers.txt | Telnet -Port 80
Successfully connected to WebServer on Port: 80
Could not connect to DC1 on Port: 80
Successfully connected to Linux-Box on Port: 80

Congratulations! Your Telnet module is working as expected. The good thing about this module is that you can use same command that used to work with cmd.exe.

This cmdlet is an ideal way to work on client’s servers where you do not have authority (or you do not want) to enable Telnet-Client Windows feature for any reason.



Microsoft Certified Professional | Cisco Certified Network Associate

4 Comments

  • Amol Dhaygude

    Your script is marvelous, my requirement is port in bulk instead of servername, so how I modify this script

    • Hi Amol,
      You could use the following modified script:


      < # .Synopsis Tests the connectivity between two computers on a TCP Port .Description The Telnet command tests the connectivity between two computers on a TCP Port. By running this command, you can determine if specific service is running on Server. .Parameter
      This is a required parameter where you need to specify a computer name which can be localhost or a remote computer

      .Parameter This is a required parameter where you need to specify a TCP port you want to test connection on.

      .Parameter
      This is an optional parameter where you can specify the timeout in milli-seconds. Default timeout is 10000ms (10 seconds)

      .Example
      Telnet -ComputerName DC1 -Port 3389
      This command reports if DC1 can be connected on port 3389 which is default port for Remote Desktop Protocol (RDP). By simply running this command, you can check if Remote Desktop is enabled on computer DC1.

      .Example
      Telnet WebServer 80
      This command tells you if WebServer is reachable on Port 80 which is default port for HTTP.

      .Example
      Get-Content C:\Computers.txt | Telnet -Port 80
      This command will take all the computernames from a text file and pipe each computername to Telnet Cmdlet to report if all the computers are accessible on Port 80.
      #>
      Function Telnet{

      [CmdletBinding()]
      param(
      [Parameter(Mandatory=$true,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true)]
      [Alias ('HostName','cn','Host','Computer')]
      [String]$ComputerName='localhost',
      [Parameter(Mandatory=$true,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true)]
      [int32[]]$Port,
      [int32] $Timeout = 10000
      )

      Begin {}

      Process {
      foreach($p in $port) {
      Try {
      $tcp = New-Object System.Net.Sockets.TcpClient
      $connection = $tcp.BeginConnect($ComputerName, $p, $null, $null)
      $connection.AsyncWaitHandle.WaitOne($timeout,$false) | Out-Null
      if($tcp.Connected -eq $true) {
      Write-Host "Successfully connected to Host: `"$ComputerName`" on Port: `"$p`"" -ForegroundColor Green
      }
      else {
      Write-Host "Could not connect to Host: `"$ComputerName `" on Port: `"$p`"" -ForegroundColor Red
      }
      }

      Catch {
      Write-Host "Unknown Error" -ForegroundColor Red
      }

      }

      }
      End {}
      }

      See this image to know how to use it:
      Modified Telnet Cmdlet

  • alex

    Hello it shows me bellow error:
    Any advise ?

    PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules> Import-Module .\Telnet
    At C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Telnet\Telnet.psm1:7 char:114
    + … the timeout in milli-seconds. Default timeout is 10000ms (10 seconds)
    + ~~~~~~~
    Unexpected token ‘seconds’ in expression or statement.
    At C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Telnet\Telnet.psm1:7 char:113
    + … the timeout in milli-seconds. Default timeout is 10000ms (10 seconds …
    + ~
    Missing closing ‘)’ in expression.
    At C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Telnet\Telnet.psm1:7 char:121
    + … the timeout in milli-seconds. Default timeout is 10000ms (10 seconds)
    + ~
    Unexpected token ‘)’ in expression or statement.
    + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

    Import-Module : The specified module ‘.\Telnet’ was not loaded because no valid module file was found in any module directory.
    At line:1 char:1
    + Import-Module .\Telnet
    + ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ResourceUnavailable: (.\Telnet:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

    • Hi Alex,

      Did you follow the guide exactly or made some changes at your own? By the way, the following line in error shows exactly where the error is:

      At C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Telnet\Telnet.psm1:7 char:114

      Double check your script to find out what is causing it.

Leave a Reply