Friday, February 13, 2015

"Telnet" in PowerShell Style

I guess that I'm not the only one that had a connection test to perform and found out that the Telnet Client is not installed on the system.

And again, Powershell to the rescue...

I decided to write a small PowerShell function to perform the same concavity test as Telnet will, and in order to perform this test we will leverage the System.Net.Sockets.TcpClient .NET object,
You may read some more about it at:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

And now for the function:
 
# PowerShell PSTelnet function

function PSTelnet([string]$Destination, [int]$Port) {
  
  # Create a TcpClient .NET object  
  $TCPClient = New-Object System.Net.Sockets.TcpClient
    
    # Try & Catch
    try {
          $TCPClient.Connect($Destination, $Port)
        } # END try
    catch [System.Net.Sockets.SocketException] {
            Write-Host -ForegroundColor Red "`nPSTelnet failed to connect with the following error:`n"
            Write-Output -ForegroundColor Red $Error.Item(0)
          } #END cache
  
  # Test if the connection established
  if ($TCPClient.Connected) {
    Write-Host -ForegroundColor Green "`nPSTelnet Successfully Connected"
    } # END if

  # Close and reset the connection
  $TCPClient.Close()

} # END of function

### Example of usage

PSTelnet -Destionation 127.0.0.1 -Port 445

### Example of output

PSTelnet Successfully Connected

Hope this helps,

Enjoy.