Cool PowerShell Script Replicates Telnet

Lee Holmes has a cool script to reproduce telnet-like functionality via the TcpClient object in PowerShell.

## Connect-Computer.ps1 
## Interact with a service on a remote TCP port 
    [string] $remoteHost = "localhost", 
    [int] $port = 23

    ## Open the socket, and connect to the computer on the specified port 
    write-host "Connecting to $remoteHost on port $port" 
    $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port) 
    if($socket -eq $null) { return; } 

    $stream = $socket.GetStream() 
    $writer = new-object System.IO.StreamWriter($stream) 

    $buffer = new-object System.Byte[] 1024 
    $encoding = new-object System.Text.AsciiEncoding 

       ## Allow data to buffer for a bit 
       start-sleep -m 500 

       ## Read all the data available from the stream, writing it to the 
       ## screen when done. 
          $read = $stream.Read($buffer, 0, 1024)    
          write-host -n ($encoding.GetString($buffer, 0, $read))  

       ## Read the user's command, quitting if they hit ^D 
       $command = read-host 
       ## Write their command to the remote host      
    ## Close the streams 

This solves the problem of telnet.exe crashing conhost.exe when using Console2.


I tweaked Lee’s code to use try/finally which obviates the need for a special escape sequence to clean up the TCP resources.

3 Responses to Cool PowerShell Script Replicates Telnet

  1. vivek says:

    I am getting unwanted characters along with the ouput:
    Before the first command is inserted i, i am getting these symbols:


    Please help: how can i stop getting this weird symbols

  2. Pingback: Backup Network Configuration with PowerShell | System Center ZA

  3. Pingback: Backup Network Configuration with PowerShell | System Center Guy ZA

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 137 other followers

%d bloggers like this: