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
            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

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 -SearchRoot ” | %{.\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 -SearchRoot ” | %{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.



The Admin Guy