Check if port is open not using Test-NetConnection

Daniel Sajdyk 41 Reputation points
2021-09-27T19:31:18.83+00:00

Hello,

I wrote script to check if ports one remote machines are open. For this task I use cmdlet Test-NetConnection doing its job in loop.
It works fine, but this is very slow solution. I need to check about 30 servers with full range of port and this takes about 48h...

And my question is - how can I speed up this process. I think that .net could help me this, but I'm not sure, and don't know how should I do this....

Ps. I know that is dedicated tool for that like nmap, but due to many different reasons I need to have my solution doing things which nmap can't do.

Best Regards

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,430 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,416 Reputation points
    2021-09-27T20:07:34.86+00:00

    If all the ports you're testing use TCP and not another protocol like ICMP the try using .Net's System.Net.Sockets.TcpClient. Here's just one of the examples you can find: fast-tcp-port-check-in-powershell.html

    You can also decrease the duration of your testing by introducing some level of parallelism into the process. Have a look at using Start-Job. Keep the number of concurrent jobs to a reasonable number (based on the capabilities of the machine from which you're running the script). Collect the data when the last job completes.

    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Limitless Technology 39,461 Reputation points
    2021-09-29T13:54:54.69+00:00

    Hello,

    Thank you for your question.

    Additionally , I would suggest you to run Test-Connection script from multiple PowerShell windows or you can create multiple Task scheduler to run at multiple times for different servers .

    You can also run the script on the servers having same subnet or same ip range so that it will speed-up.


    --If the reply is helpful, please Upvote and Accept as answer--

    0 comments No comments

  2. Daniel Sajdyk 41 Reputation points
    2021-09-29T14:01:09.363+00:00

    Hello,

    Thank you both for your replies.
    I looked at solution posted by @Rich Matheisen , and it look that it hits right in my needs ;)
    I changed the TimeOut value to 1s and use parralell option, and now it is working significantly fast :)

    Thank you both :)
    Best Regards

    0 comments No comments