Skip to content

Instantly share code, notes, and snippets.

@bgelens
Last active October 24, 2023 12:47
Show Gist options
  • Save bgelens/530efed9cddd09a54a40 to your computer and use it in GitHub Desktop.
Save bgelens/530efed9cddd09a54a40 to your computer and use it in GitHub Desktop.
function Test-NetPort {
[CmdletBinding()]
[OutputType([Boolean])]
param (
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[String] $ComputerName,
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[Int] $Port,
[Int] $Timeout = 2
)
process {
$TCPConnect = New-Object -TypeName System.Net.Sockets.TcpClient
Write-Verbose -Message "Attempting connection to computer: $ComputerName on TCP port: $Port"
try {
$TCPConnect.ConnectAsync($ComputerName,$Port).Wait([timespan]::FromSeconds($Timeout))
} catch [ArgumentOutOfRangeException] {
Write-Error -Message 'Port defined was out of range' -ErrorAction Continue
$false
} catch [AggregateException] {
Write-Warning -Message $_.Exception.InnerException.Message
$false
} catch {
Write-Error -ErrorRecord $_ -ErrorAction Continue
} finally {
$TCPConnect.Dispose()
}
}
}
Test-NetPort -ComputerName dc.lab.local -Port 3389
'dc.lab.local' | Test-NetPort -Port 389
[PSCustomObject]@{ComputerName = 'dc.lab.local';Port='5985'} | Test-NetPort
#waits for port to become available or until 5 minutes have passed
$i = 0
do {
$i++
$WSMAN = Test-NetPort -ComputerName dc.lab.local -Port 5985 -Timeout 3
} until ($WSMAN -or $i -eq 100)
@bgelens
Copy link
Author

bgelens commented Jul 30, 2015

Requires .NET 4.5.
Test-NetConnection does not have a timeout option and only allows port check from Windows 2012R2+
Specially handy in do until loop to check if port has become available (no need for start-sleep).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment