In the hacking world, we know that Tools such as NMAP gives you a breakdown of the open ports, services etc. which is great and you can also check an open port using Telnet, but if you are restricted with tools and cannot add new features onto the Windows Servers, why not use PowerShell to check open ports. I put together a script that will run a test against a server and you can specify the ports. You may want to check upper ports such as port 5000 or port 9000 to 10000 for custom applications or you can simply check port 1-100 which is the default set in the script.

The script runs and displays the info in a Grid which is clean, it outputs the following information:

  • TargetHost
  • Port
  • Status (Open or Closed)

Below is an example of the output against one of my Test Exchange Servers:

Find the open ports of a host using powershell

In the background in PowerShell, you will see warnings about ports that are not responding but this is not an error:

Find the open ports of a host using powershell

SCRIPT

The script has three (3) sections that need to be modified according to your requirements, they are as follows:

  • $TargetHost (default set to localhosts) – Change this to the server you want to test
  • $startPort – (default set to 1) – Change this to the number you want to start scanning from
  • $endPort – (default set to 100) – Change this to the number you want to end the scanning on

Below is the script:

param (
    [string]$targetHost = "Server1",
    [int]$startPort = 1,
    [int]$endPort = 100
)

function Test-Port {
    param (
        [string]$targetHost,
        [int]$port
    )

    $result = Test-NetConnection -ComputerName $targetHost -Port $port

    [PSCustomObject]@{
        TargetHost = $targetHost
        Port = $port
        Status = if ($result.TcpTestSucceeded) { 'Open' } else { 'Closed' }
    }
}

$results = @()

for ($port = $startPort; $port -le $endPort; $port++) {
    $results += Test-Port -targetHost $targetHost -port $port
}

$results | Out-GridView

The script is responsive, however it will take longer to bring up the Grid if you select a large number of ports to scan.

Hope it helps.

Discover more from Everything-PowerShell

Subscribe now to keep reading and get access to the full archive.

Continue reading