Test-port

Well I needed to check if a specific port was reachable on a set of servers.
This script is created for checking if a specific port is accessible or not.

Parameters used :
-server <server1,server2> : Provide server(s) to check
-port <port> : Provide the port to check
-list <list.csv> : Also a list of servers can be checked all at once. The list does need a header server;port
-trace : This option will enable tracing of the script and show all the steps and data collected (debug)
-outfile <Outfile.csv> : This will export the resolved data to a CVS-file.

<#

.SYNOPSIS
This is a simple Powershell script to check si a specific TCP port is open

.DESCRIPTION
This script allows you to check specifi TCP ports if they are reachable.
The output is like the connection status that is returned from the system.
eg : host unreachable

.EXAMPLE
Single Server
    test-port.ps1 -server <Servername> -Port xxx

.EXAMPLE
Localhost
    test-port.ps1 -Port xxx

.NOTES
 Versioning : 
 V0.0.1 WS 16-12-2013 Initial
 v1.0.0 WS 16-12-2013 
 v1.0.1 WS 16-12-2013
 v1.0.2 WS 16-12-2013 Added debugging
 V1.0.3 WS 17-12-2013 Added output to csv 

.LINK
http://www.usful-it.nl (Wessel van Sandwijk)

#>
###############################################################################
# Script Title : Test for open ports
###############################################################################
# Author : Wessel van Sandwijk (12-2013)
###############################################################################
# Version : V1.0.3
###############################################################################
# Usage :
#
#    Single Server
#        test-port.ps1 -server <Servername> -Port <##>
#
#    Localhost
#        test-port.ps1 -Port <##>
#
#    Multiple servers using a server list
#        Server list must contain the following values
#         Server;Port
#         <servername>;<Port>
#
#        test-port.ps1 -list <filename>
#
###############################################################################
#
# Variables to use :
#
# -Server <srv1>,<srv2>,....
#    Multiple servers can be used for port checking
# -port <port1>,<port2>,.....
#    Multiple ports can be used for port checking
# -List <Filename>
#    Filename with servers (Header of the files is mandatory
#    Server;Port
#    <server>;<port>
#    in this mode the -server and -port are ignored.
# -debug
#    Add to the commandline to enable debugging of the script
#    Default is no debugging of the script.
# -outfile
#    output to a filename in csv format
#
###############################################################################
# Versioning : 
# V0.0.1 WS 16-12-2013 Initial
# v1.0.0 WS 16-12-2013 
# v1.0.1 WS 16-12-2013
# v1.0.2 WS 16-12-2013 Added debugging
# V1.0.3 WS 17-12-2013 Added output to csv 
###############################################################################

###############################################################################
# Future options
###############################################################################
# 1. Multiple ports from csvfiles
###############################################################################

###############################################################################
# CmdLet Parameters
###############################################################################

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$False)]
   [Array]$Server,
   [Array]$port,
   [String]$list,
   [switch]$trace,
   [String]$outfile
      )

###############################################################################
# Error handling
###############################################################################

###############################################################################
# Functions
###############################################################################
Function Trace($type,[string]$message) {
    if ($trace) {
        if ($type -eq "1") {
            Write-host $message -ForegroundColor Yellow -NoNewline
            }
        if ($type -eq "2") {
            Write-host $message -BackgroundColor Green -ForegroundColor Yellow
            }
        if ($type -eq "3") {
            Write-host $message}
        }
    }

function Test-port([string]$server,$port) # Actual testing the Port 
    {
            Trace 1 "Processing $server | $port | "

            $obj=New-Object PSObject
            $obj | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $Server
            $obj | Add-Member -MemberType NoteProperty -Name "Port" -Value $port
            try{
                $contest = Test-Connection -ComputerName $server -count 1 -ErrorAction SilentlyContinue           

                try{
                        (new-object Net.Sockets.TcpClient).Connect($server, $port)
                        $Response = "Accepted"
                        $obj | Add-Member -MemberType NoteProperty -Name "Response" -Value $Response
                        Trace 2 $Response
                        }
                catch [Exception] {
                        $Response = $_.Exception.Message 
                        $obj | Add-Member -MemberType NoteProperty -Name "Response" -Value $Response
                        Trace 2 $Response
                        }
                }
            catch {
                Trace 4 $_.Exception.Message
                $response = $_Exeception.Message
                $obj | Add-Member -MemberType NoteProperty -Name "Response" -Value $Response
                }
            Trace 3 "------------------------------------------------------------------------------------------------------"
            $global:totalServers += $obj
    }

Function UseList($path) # if the -list option is used.
    {
    Write-host "List Parameter used | $Path" -BackgroundColor Blue -ForegroundColor Yellow
    $implist = import-csv -path $list -Delimiter ";"
    $impListcount = $implist.count
    $message = "{0:p0} completed, remaining time {1} Processing : {2} items" -f ($i/$implistcount), $item, $implistcount
    for ($i=1;$i -le $implistcount){
        foreach ($item in $implist) {
        $Servername = $item.Server
        Write-Progress -Activity "Processing Port Test" -status "Items to process : $($implistcount - $i)" -percentComplete ($i / $implistcount*100) -CurrentOperation "Processing $($($item).server) on port $($($item).port)"
        $itemport = $($item.port) -split ","
        foreach ($itport in $itemport) {
            test-port $($item.Server) $($itport)
            }
        $i++}
        }
    }

###############################################################################
# Script
###############################################################################

$global:totalServers = @()
if ($list){
    if ($port -or $server) {
        Write-host "Server and Port are ignored if using the -list option" -BackgroundColor Blue -ForegroundColor White
        }
    UseList $list
    }

    Else{

    if (!$port){
            Write-host "The port is mandatory"
            Write-host "please add the appropiate parameters" -BackgroundColor Blue -ForegroundColor White}
    else {
        if ($server) {
                foreach ($item in $server) {
                    foreach ($itPort in $port){

                        Test-port $item $itport
                        }
                    }
            }
        Else {
            write-host "Server used : Localhost with port : $port"
            }
        }

    }

###############################################################################
# Screen Output
###############################################################################

if ($outfile){ 
    $global:totalServers | export-csv $outfile -NoTypeInformation}
    Else
    {
    $global:totalServers | ft -AutoSize}

 

or download the Script.

[wpdm_file id=3]

About the Author

wvsandwijk

I am a Technical Specialist - Cloud Infrastructures from the Netherlands. My Skills are mainly PowerShell, VMWare, Hyper-V, Microsoft System Center products and Windows Azure Pack. I work for a company in Utrecht The Netherlands.

No Comments

Comments are closed.