Home > Powershell Scripts > Powershell port ping function

Powershell port ping function

As a variation of my previously posted Portscan with powershell i wrote the following function

Function Port-Ping {
    param([Array]$hostlist,[Array]$ports,[Int]$timeout = "50")
    $ErrorActionPreference = "SilentlyContinue"
    $ping = new-object System.Net.NetworkInformation.Ping
    foreach ($ip in $hostlist) {
        $rslt = $ping.send($ip,$timeout)
        if (! $?){
            Write-Host "Host: $ip - not found" -ForegroundColor Red
        }
        else {
            if ($rslt.status.tostring() –eq “Success”) {
                write-host "Host: $ip - Ports: " -foregroundColor Green -NoNewline
                foreach ($port in $ports){
                    $socket = new-object System.Net.Sockets.TcpClient($ip, $port)
                    if ($socket –eq $null) {
                        write-host "$port," -ForegroundColor Red -NoNewline
                    }
                    else {
                        write-host "$port,"-foregroundcolor Green -NoNewline
                        $socket = $null
                    }
                }
            Write-Host
            }
            else {
                write-host "Host: $ip - down" -ForegroundColor Red
            }
        }
    }
    Write-Host ""
    $ping = $null
}

This function is great when you need a fast overview of servers and the ports they have open. In my case I needed to check 3 ports on 100+ servers. The output of this function is color-coded  as the previous script (hence not suitable for piping)

The functions usage is like this:

PS> .\PortPing.ps1 <server> <port> <timeout>

Alternatively an array of servers can be created and used with the function:

Say you need to find whether all AD computer objects in a particular OU are alive and responding to port 3389 (Remote Desktop)

(I’m using Quest Download ActiveRoles Management Shell for Active Directory in this example)

PS> Get-QADComputer -service <Domain> -SearchRoot ‘<Domain/OU/OU>’ | %{.\PortPing.ps1 $_.Name 3389 100}

Inspired by Jeffery Hicks, I added the function to a dot source file, which is loaded with my PowerShell profile, which would then have this usage:

PS> Get-QADComputer -service <Domain> -SearchRoot ‘<Domain/OU/OU>’ | %{Port-Ping $_.Name 3389 100}

As a server administrator, this function gives me the rapid overview that I need to check multiple servers and their ports.

 

Regards

The Admin Guy

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: