Last active
August 5, 2016 11:06
-
-
Save dhcgn/44acdddbaea24d2f367d85a00389368c to your computer and use it in GitHub Desktop.
powershell script to test the response of a computer to a specific TCP port (After Windows 8.1 use Test-NetConnection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Test the response of a computer to a specific TCP port | |
.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 | |
{ | |
$time = Measure-Command -Expression { | |
$Connection.Connect($Computer, $TCPPort) | |
$stream = $Connection.Close() | |
$Response = "OK: Opened" | |
} | |
if ($Connection.Connected) { | |
$Connection.Close() | |
$Response = "OK: Opened and Closed" | |
} | |
} | |
catch [System.Management.Automation.MethodInvocationException] | |
{ | |
$Response = "Error: "+$_.Exception.Message | |
} | |
$Connection = $null | |
$hash = @{ | |
ComputerName = $Computer | |
Port = $TCPPort | |
Response = $Response | |
Duration = $time | |
DurationMs = $time.Milliseconds | |
} | |
$Object = New-Object PSObject -Property $hash | |
$TCPObject += $Object | |
} | |
} | |
} | |
end { | |
Write-Output $TCPObject | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment