Testing TCP Port Response from PowerShell
Recently I was listening to the PowerScripting Podcast and Hal mentioned a Test-TCPPort function he had put together a while back. I had a similar need to be able to test a bunch of machines post reboot, that they had come back successfully and a Ping test wouldn’t do since that didn’t necessarily mean that Windows has successfully booted :-)
So taking inspiration from that post I put together the following script (I convert it to a function for my own use, but it’s easier for my colleagues to use as a script) which will test by default RDP response from servers and report the results. A few examples of how to use it:
Test a single server
Test-TCPPortConnection -ComputerName Server01 | Format-Table -AutoSize
Testing multiple servers
Get-Content servers.txt | Test-TCPPortConnection | Format-Table -AutoSize
Testing multiple servers on multiple ports, 22 and 443, and exporting the results to csv
Get-Content servers.txt | Test-TCPPortConnection -Port 22,443 | Export-Csv Ports.csv -NoTypeInformation
Here’s the code you can use.
Update 08/10/2013: Following some feedback in the comments, I’ve updated this to a function and to cater for multiple port requirements. The examples above have been updated too:
.DESCRIPTION Test the response of a computer to a specific TCP port
.PARAMETER ComputerName Name of the computer to test the response for
.PARAMETER Port TCP Port number(s) to test
.INPUTS System.String. System.Int.
.OUTPUTS None
.EXAMPLE PS C:\\> Test-TCPPortConnection -ComputerName Server01
.EXAMPLE PS C:\\> Get-Content Servers.txt | Test-TCPPortConnection -Port 22,443 #>
\[CmdletBinding()\]\[OutputType('System.Management.Automation.PSObject')\]
param(
\[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to test", ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)\] \[Alias('CN','\_\_SERVER','IPAddress','Server')\] \[String\[\]\]$ComputerName,
\[Parameter(Position=1)\] \[ValidateRange(1,65535)\] \[Int\[\]\]$Port = 3389 )
begin { $TCPObject = @() }
process {
foreach ($Computer in $ComputerName){
foreach ($TCPPort in $Port){
$Connection = New-Object Net.Sockets.TcpClient
try {
$Connection.Connect($Computer,$TCPPort)
if ($Connection.Connected) {
$Response = “Open” $Connection.Close() }
}
catch \[System.Management.Automation.MethodInvocationException\]
{ $Response = “Closed / Filtered” }
$Connection = $null
$hash = @{
ComputerName = $Computer Port = $TCPPort Response = $Response } $Object = New-Object PSObject -Property $hash $TCPObject += $Object
} } }
end {
Write-Output $TCPObject } }