You can check the connection to an IP address and a specific port in PowerShell using a few methods, with Test-NetConnection being the most modern and recommended way.
Here are the common methods:
1. Recommended: Using Test-NetConnection (PowerShell 4.0+)
This is the easiest and most robust way if you're running PowerShell 4.0 or newer (which is most modern Windows systems).
# Basic check to IP and Port
Test-NetConnection -ComputerName 192.168.1.100 -Port 80
# To check specific properties (e.g., just if the TCP test succeeded)
$connectionResult = Test-NetConnection -ComputerName 192.168.1.100 -Port 80 -InformationLevel Detailed
if ($connectionResult.TcpTestSucceeded) {
Write-Host "Connection to 192.168.1.100 on port 80 succeeded!" -ForegroundColor Green
} else {
Write-Host "Connection to 192.168.1.100 on port 80 failed." -ForegroundColor Red
Write-Host "Error Message: $($connectionResult.FailureMessage)"
}
# With a timeout (e.g., 2 seconds)
Test-NetConnection -ComputerName 192.168.1.100 -Port 3389 -TimeoutSeconds 2
Explanation:
-ComputerName: The IP address or hostname you want to connect to.
-Port: The specific TCP port you want to test.
-InformationLevel Detailed: Provides much more information, including TcpTestSucceeded, PingSucceeded, Latency, SourceAddress, etc.
-TimeoutSeconds: Specifies how long (in seconds) the cmdlet should wait for a response before timing out.
Output Example for Success (-InformationLevel Detailed):
ComputerName : 192.168.1.100
RemotePort : 80
InterfaceAlias : Ethernet
SourceAddress : 192.168.1.50
PingSucceeded : True
PingReplyDetails : PING: bytes=32 time=0ms TTL=128
TcpTestSucceeded : True
Output Example for Failure:
WARNING: TCP connect to 192.168.1.100:80 failed
ComputerName : 192.168.1.100
RemotePort : 80
InterfaceAlias : Ethernet
SourceAddress : 192.168.1.50
PingSucceeded : True
PingReplyDetails : PING: bytes=32 time=0ms TTL=128
TcpTestSucceeded : False
FailureMessage : No connection could be made because the target machine actively refused it.
2. Using System.Net.Sockets.TcpClient (For Older PowerShell Versions or More Control)
If Test-NetConnection is not available (e.g., PowerShell 3.0 or earlier), or if you need finer-grained control over the connection, you can use the .NET TcpClient class directly.
function Test-TcpPort {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$IPAddress,
[Parameter(Mandatory=$true)]
[int]$Port,
[int]$TimeoutSeconds = 3 # Default timeout
)
$tcpClient = New-Object System.Net.Sockets.TcpClient
$isConnected = $false
try {
# Create an IPEndPoint object
$ipEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($IPAddress), $Port)
# Begin connection attempt (async)
$connectResult = $tcpClient.BeginConnect($ipEndPoint, $null, $null)
# Wait for the connection attempt to complete within the timeout
$connectResult.AsyncWaitHandle.WaitOne($TimeoutSeconds * 1000, $false) | Out-Null
if ($tcpClient.Connected) {
$tcpClient.EndConnect($connectResult) # Complete the asynchronous connection
$isConnected = $true
} else {
# If not connected, it likely timed out or was refused
Write-Warning "Connection to $IPAddress:$Port timed out after $TimeoutSeconds seconds."
}
}
catch [System.Net.Sockets.SocketException] {
Write-Warning "Socket error connecting to $IPAddress:$Port: $($_.Exception.Message)"
}
catch [System.Exception] {
Write-Warning "An unexpected error occurred connecting to $IPAddress:$Port: $($_.Exception.Message)"
}
finally {
if ($tcpClient -ne $null) {
$tcpClient.Dispose() # Important to release resources
}
}
return $isConnected
}
# --- Examples of using the function ---
# Test a successful connection (e.g., an active web server)
if (Test-TcpPort -IPAddress "8.8.8.8" -Port 53) { # Google DNS
Write-Host "Successfully connected to 8.8.8.8 on port 53." -ForegroundColor Green
} else {
Write-Host "Failed to connect to 8.8.8.8 on port 53." -ForegroundColor Red
}
# Test a failed connection (e.g., a closed port)
if (Test-TcpPort -IPAddress "192.168.1.100" -Port 12345) {
Write-Host "Successfully connected to 192.168.1.100 on port 12345." -ForegroundColor Green
} else {
Write-Host "Failed to connect to 192.168.1.100 on port 12345." -ForegroundColor Red
}
# Test with a shorter timeout
if (Test-TcpPort -IPAddress "192.168.1.100" -Port 22 -TimeoutSeconds 1) {
Write-Host "Successfully connected to 192.168.1.100 on port 22 within 1 second." -ForegroundColor Green
} else {
Write-Host "Failed to connect to 192.168.1.100 on port 22 within 1 second." -ForegroundColor Red
}
Explanation:
- This function creates a
System.Net.Sockets.TcpClient object.
- It attempts to connect asynchronously using
BeginConnect and then waits for the connection to complete or for a specified timeout using AsyncWaitHandle.WaitOne(). This is crucial for implementing a custom timeout for the connection attempt itself.
$tcpClient.Connected property tells you if the connection was established.
- The
try/catch/finally block is essential for proper error handling and ensuring the TcpClient object is always disposed of, preventing resource leaks.
3. Test-Connection (Ping Only - Not a Port Check)
Be aware that Test-Connection (which is PowerShell's version of ping) only checks for ICMP (ping) connectivity, not TCP port connectivity. An IP address might respond to ping but have all its ports blocked, or vice-versa if ICMP is blocked but a service port is open.
# This only checks if the IP responds to ping (ICMP), NOT if a port is open.
Test-Connection -ComputerName 192.168.1.100 -Count 1 -ErrorAction SilentlyContinue
# To check if ping succeeded:
if ((Test-Connection -ComputerName 192.168.1.100 -Count 1 -ErrorAction SilentlyContinue).StatusCode -eq 0) {
Write-Host "Ping to 192.168.1.100 succeeded."
} else {
Write-Host "Ping to 192.168.1.100 failed."
}
In summary:
- For most modern use cases,
Test-NetConnection -ComputerName <IP> -Port <Port> is the best and simplest way.
- If you need a custom timeout for the connection attempt or are on older PowerShell, the
TcpClient function is a robust alternative.
Test-Connection is only for ICMP (ping) and will not tell you if a specific port is open.