What if you want to check for open ports on a server, but you don’t have telnet installed on your management server?

Yes! Use PowerShell! But how?

Thankfully PowerShell allows us to use .NET classes because there isn’t a PowerShell Cmdlet that can do this (as far as I know). The class that I used is described here: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

A short explanation…

1. First we create an TCP object

2. With this object we can try to connect with the method TcpClient.Connect(IPAddress, Int32)

3. If a connection is possible, we go to the next line and confirm that a connection is made. If NO connection is possible, it throws an exception and we are send to the catch part of the code.

That’s it! Ok, ok… Its a bit more code than “telnet 127.0.0.1 80″… But hey… at least it’s possible! 🙂

try 
{ 
  $tcp=new-object System.Net.Sockets.TcpClient 
  $tcp.connect("localhost",80)
  Write-Host "Connection possible!" -ForegroundColor Green
  $tcp.close() 
} 
catch 
{ 
  Write-Host "Cannot connect!" -ForegroundColor Red
}

Thank you for reading!

Bart