Windows powershell проверить порт

В PowerShell для проверки доступности порта на удаленном компьютере можно использовать командлет Test-NetConnection. Этот командлет позволяет проверить доступность удаленного сервера или службы на нем, протестировать блокируется ли TCP порт файерволами, проверить доступность по ICMP и маршрутизацию. По сути, командлет Test-NetConnection позволяет заменить сразу несколько привычных сетевых утилит: ping, traceroute, telnet, сканер TCP портов и т.д.

Содержание:

  • Проверка доступности TCP порта с помощью Test-NetConnection
  • PowerShell: проверка открытых портов на нескольких IP хостах
  • IP сканер сети на PowerShell
  • Вывести список открытых портов в Windows

Проверка доступности TCP порта с помощью Test-NetConnection

Командлет Test-NetConnection можно использовать только для проверки TCP портов. Например, чтобы проверить, что на почтовом сервере открыт порт TCP 25 (SMTP протокол), выполните команду:

Test-NetConnection -ComputerName msk-msg01 -Port 25

Примечание. С помощью командлета Test-NetConnection можно проверить только TCP соединение, для проверки доступности UDP портов он не применим.

В сокращенном виде аналогичная команда выглядит так:

TNC msk-mail1 -Port 25

Test-NetConnection - прверка ответа от TCP порта

Разберем результат команды:

ComputerName : msk-msg01 RemoteAddress : 10.10.1.7 RemotePort : 25 InterfaceAlias : CORP  

SourceAddress : 10.10.1.70 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : True 

Как вы видите, командлет выполняет разрешение имени сервера в IP адрес, выполняется проверка ответа ICMP (аналог ping) и проверка ответа от TCP порта (доступность). Указанный сервер доступен по ICMP (
PingSucceeded = True
) и 25 TCP порт также отвечает (
RemotePort=25, TcpTestSucceeded= True
).

Примечание. Если команда вернула PingSucceeded=False и TcpTestSucceeded= True, скорее всего означает, что на удаленном сервере запрещен ICMP Ping.

Если выполнить команду Test-NetConnection без параметров, выполнится проверка наличия подключения к интернету на компьютере (проверяется доступность узла internetbeacon.msedge.net):

Test-NetConnection проверить достуа в интернет на компьютере

Для вывода детальной информации при проверки удаленного TCP порта можно добавить опцию -InformationLevel Detailed:

TNC 192.168.31.102 -Port 3389 -InformationLevel Detailed

test-netconneciton detailed - подробная информация о доступности удаленного порта

Доступность популярных сервисов Windows на удаленном компьютере (HTTP, RDP, SMB, WINRM) можно проверить с помощью параметра CommonTCPPort.

Например, чтобы проверить доступность веб-сервера, можно использовать команду:

Test-NetConnection -ComputerName winitpro.ru -CommonTCPPort HTTP

Или проверить доступность стандартного RDP порта (TCP/3389):

Test-NetConnection msk-rds1 –CommonTCPPort RDP

Можно вывести все параметры, которые возвращает командлет Test-NetConnection:

Test-NetConnection msk-man01 -port 445|Format-List *

Test-NetConnection все свойства

Если нужна только информация по доступности TCP порта, в более лаконичном виде проверка может быть выполнена так:

TNC msk-mail1 -Port 25 -InformationLevel Quiet

Командлет вернул True, значит удаленный порт доступен.

TNC InformationLevel Quiet

Совет. В предыдущих версиях Windows PowerShell (до версии 4.0) проверить доступность удаленного TCP порта можно было так:

(New-Object System.Net.Sockets.TcpClient).Connect('msk-msg01', 25)

New-Object System.Net.Sockets.TcpClient

Командлет Test-NetConnection можно использовать для трассировки маршрута до удаленного сервера при помощи параметра –TraceRoute (аналог команды трассировки маршрута tracert). С помощью параметра –Hops можно ограничить максимальное количество хопов при проверке.

Test-NetConnection msk-man01 –TraceRoute

Командлет вернул сетевую задержку при доступе к серверу в миллисекундах (
PingReplyDetails (RTT) : 41 ms
) и все IP адреса маршрутизаторов на пути до целевого сервера.

Test-NetConnection TraceRoute

PowerShell: проверка открытых портов на нескольких IP хостах

С помощью PowerShell можно проверить доступность определенного порта на нескольких компьютерах. Сохраните список серверов или IP адресов в текстовый файл servers.txt.

Например, ваша задача – найти сервере на которых не отвечает или закрыт порт TCP/25:

Get-Content c:\Distr\servers.txt |  where { -NOT (Test-Netconnection $_ -Port 25  -InformationLevel Quiet)}| Format-Table –AutoSize

Вы можете использовать PowerShell в качестве простейшую систему мониторинга, которая проверяет доступность серверов и выводит уведомление, если один из серверов недоступен.

Например, вы можете проверить доступность основных служб на всех контроллерах домена в AD (список DC можно получить командлетом Get-ADDomainController). Проверим следующие службы на DC (в утилите PortQry есть аналогичное правило Domain and trusts):

  • RPC – TCP/135
  • LDAP – TCP/389
  • LDAP – TCP/3268
  • DNS – TCP/53
  • Kerberos – TCP/88
  • SMB – TCP/445

$Ports = "135","389","636","3268","53","88","445","3269", "80", "443"
$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address
ForEach($DC in $AllDCs){
Foreach ($P in $Ports){
$check=Test-NetConnection $DC.Ipv4address -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)
{Write-Host $DC.hostname $P -ForegroundColor Green -Separator " => "}
else
{Write-Host $DC.hostname $P -Separator " => " -ForegroundColor Red}
}
}

Скрипт проверит указанные TCP порты на контроллерах домена, и, если один из портов недоступен, выделит его красным цветом (можно запустить данный PowerShell скрипт как службу Windows).

powershell: test-netconnection проверить порты на конроллерах домена

IP сканер сети на PowerShell

Вы можете реализовать простой IP сканер, которые сканирует удаленные хосты или IP подсети на открытые/закрытые TCP порты.

Чтобы просканировать диапазон IP адресов с 10.10.10.5 до 10.10.10.30 и вывести компьютеры, на которых открыт порт 3389:

foreach ($ip in 5..30) {Test-NetConnection -Port 3389 -InformationLevel "Detailed" 10.10.10.$ip}

Можно просканировать диапазон TCP портов (от 1 до 1024) на указанном сервере:

foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}

powershell сканирование открытых сетевых портов

Вывести список открытых портов в Windows

Если вам нужно вывести список портов, открытых на локальном компьютере, исопльзуется командлет Get-NetTCPConnection (это PowerShell-эквивалент NETSTAT). Полный список открытых портов на компьютере можно вывести так:

Get-NetTcpConnection -State Listen | Select-Object LocalAddress,LocalPort| Sort-Object -Property LocalPort | Format-Table

Если вам нужно проверить, какая программа (процесс) слушает определенный порт на вашем компьютере, выполните команду:

Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess | ft Id, ProcessName, UserName, Path

In PowerShell, you can use the Test-NetConnection cmdlet to check whether a port is available (open) on a remote computer. You can use this cmdlet to check the response and availability of a remote server or a network service, test whether the TCP port is blocked by a firewall, check ICMP availability, and routing. In fact, Test-NetConnection replaces several popular network admin tools such as ping, tracert, telnet, pathping, TCP port scanner, etc.

Contents:

  • Check for Open TCP Port with Test-NetConnection
  • PowerShell: Check for Open Ports on Multiple Hosts
  • Simple TCP/IP Port Scanner in PowerShell
  • How to List Open Ports on Windows with PowerShell

Check for Open TCP Port with Test-NetConnection

You can use the Test-NetConnection cmdlet to check only TCP ports. For example, to check that TCP port 25 (the SMTP protocol) is open on the remote mail server:

Test-NetConnection -ComputerName ny-msg01 -Port 25

Note. You can test only a TCP port connectivity by using the Test-NetConnection cmdlet. However, you cannot use the cmdlet to check the availability of the remote UDP ports.

The Test-NetConnection command has the alias TNC. The shortened version of the same command looks like this:

TNC ny-msg01 -Port 25

Test-NetConnection check remote tcp port

Let’s look at the result of the command:

ComputerName           : ny-msg01
RemoteAddress          : 10.20.1.7
RemotePort             : 25
InterfaceAlias         : CORP
SourceAddress          : 10.20.1.79
PingSucceeded          : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded       : True

As you can see, the cmdlet resolves the server name to an IP address, checks the ICMP response (similar to ping), and checks the response from the TCP port (port availability). The specified server responds via ICMP (PingSucceeded = True) and the TCP Port 25 is open (RemotePort=25, TcpTestSucceeded= True).

Note.  If the command returns PingSucceeded=False and TcpTestSucceeded= True, this most likely means that the ICMP Echo request (ping) is disabled on the remote computer.

If you run the Test-NetConnection without parameters, it will check if the computer is connected to the Internet (checks for the availability of the internetbeacon.msedge.nethost).

You can add the –InformationLevel Detailed option to display detailed information when checking a remote TCP port:

TNC 192.168.32.101 -Port 3389 -InformationLevel Detailed

Test-NetConnection: list detailed connectivity status

The cmdlet has a special parameter –CommonTCPPort, which allows you to specify the name of a known network protocol (HTTP, RDP, SMB, WINRM).

For example, to check the availability of an HTTP web server you can use the command:

Test-NetConnection -ComputerName woshub.com -CommonTCPPort HTTP

Or check the availability of a default RDP port (TCP/3389):

Test-NetConnection ny-rds1 –CommonTCPPort RDP

You can list all of the parameters that the Test-NetConnection cmdlet returns:

Test-NetConnection ny-man01 -port 445|Format-List *

Test-NetConnection all connection state properties

If you only need to see if the port is available, it can be checked more quickly:

TNC ny-msg1 -Port 25 -InformationLevel Quiet

The cmdlet returns True, which means that the remote TCP port is open.

TNC ny-msg1 -Port 25 -InformationLevel Quiet

TipIn earlier versions of Windows PowerShell (before version 4.0), you could check the availability of a remote TCP port with the command:

(New-Object System.Net.Sockets.TcpClient).Connect('ny-msg01', 25)

(New-Object System.Net.Sockets.TcpClient).Connect

You can use the Test-NetConnection cmdlet to trace a route to a remote server by using the –TraceRoute parameter (similar to the built-in tracert command in Windows). You can limit the maximum number of hops during the route check by using the -Hops parameter.

Test-NetConnection ny-man01 –TraceRoute

Cmdlet returned a summary network access delay in milliseconds   (PingReplyDetails (RTT): 41 ms) as well as all the IP addresses of the routers on the way to the destination host.

Test-NetConnection: powershell TraceRoute

PowerShell: Check for Open Ports on Multiple Hosts

You can use PowerShell to check for the availability of a specific port on a number of remote computers.  Save the list of hostnames or IP addresses in a plain text file with the name servers.txt.

For example, your task is to find hosts where the TCP/25 port is not responding or is closed on a list of servers:

Get-Content c:\PS\list_servers.txt |  where { -NOT (Test-Netconnection $_ -Port 25  -InformationLevel Quiet)}| Format-Table -AutoSize

You can use a simple monitoring PowerShell script that checks the availability of remote servers and displays a pop-up notification if any of the servers are unavailable.

For example, you can check the availability of basic services on all domain controllers during an AD health check (a DC list can be obtained with the Get-ADDomainController cmdlet). Let’s check the following services on the DC (there is a similar ‘Domain and trusts‘ rule in the PortQry tool):

  • RPC – TCP/135
  • LDAP – TCP/389
  • LDAP – TCP/3268
  • DNS – TCP/53
  • Kerberos – TCP/88
  • SMB – TCP/445

$Ports = "135","389","636","3268","53","88","445","3269", "80", "443"
$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address
ForEach($DC in $AllDCs){
Foreach ($P in $Ports){
$check=Test-NetConnection $DC.Ipv4address -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)
{Write-Host $DC.hostname $P -ForegroundColor Green -Separator " => "}
else
{Write-Host $DC.hostname $P -Separator " => " -ForegroundColor Red}
}
}

The script checks the specified TCP ports on the domain controllers, and if any of the ports are unavailable, it highlights them in red (you can run this PowerShell script as a Windows service).

Simple TCP/IP Port Scanner in PowerShell

You can use PowerShell to implement a simple IP scanner that scans remote hosts or IP subnets for open/closed TCP ports.

To scan the range of IP addresses between 192.168.1.100 and 192.168.1.150 and display computers that have port 3389 open:

foreach ($ip in 100..150) {Test-NetConnection -Port 3389 -InformationLevel "Detailed" 192.168.1.$ip}

Scan a range of TCP ports (from 1 to 1024) on a remote host:

foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}

powershell network port scanner script

How to List Open Ports on Windows with PowerShell

Use the Get-NetTCPConnection cmdlet to list the ports that are open on the local computer (this is the PowerShell equivalent of NETSTAT). A list of all open TCP ports on the computer can be viewed as follows:

Get-NetTcpConnection -State Listen | Select-Object LocalAddress,LocalPort| Sort-Object -Property LocalPort | Format-Table

If you want to find out which program (process) is listening on a specific port on your computer, use the following command (where 443 is a port number you want to check):

Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess | ft Id, ProcessName, UserName, Path

Как проверить доступность TCP-порта с помощью PowerShell?

PowerShell позволяет выполнить проверку доступности TCP-портов с помощью встроенного командлета Test-NetConnection. Пример команды:

# Проверка доступности порта TCP 80 для хоста www.bootdev.ru
Test-NetConnection www.bootdev.ru -Port 80

Успешность выполнения команды охарактеризовывает параметр TcpTestSucceeded. Значение True свидетельствует об успешности проверки, False об неудаче. В данном случае, я проверял существующий домен на открытость TCP-порта 80 (HTTP). Попробуем теперь выполнить аналогичную проверку для заведомо несуществующего хоста:

Test-NetConnection no.bootdev.ru -Port 80

Вывод команды изменился. Параметр TcpTestSucceeded отсутствует. Появился новый параметр, PingSucceeded со значением False, при проверке портов, всегда будет равен False.

На самом деле информация о параметре TcpTestSucceeded существует, просто она не попала в вывод. Осуществить вывод всех параметров можно следующей командой:

Test-NetConnection no.bootdev.ru -Port 80 | Format-List *

Вывод стал информативнее. Параметр TcpTestSucceeded снова на месте, но уже со значением равным False. Это значит, что проверяемый TCP-порт закрыт.

Использование в Cкриптах

Командная оболочка PowerShell является объектно ориентированной. То есть, любое возвращаемое значение, от любого командлета, является объектом. Следовательно, поле TcpTestSucceeded можно использовать при написании условий. Пример:

if ((Test-NetConnection www.bootdev.ru -Port 80).TcpTestSucceeded) {echo "Порт открыт :)"} else {echo "Порт закрыт :("}
if ((Test-NetConnection no.bootdev.ru -Port 80).TcpTestSucceeded) {echo "Порт открыт :)"} else {echo "Порт закрыт :("}

Как было сказано ранее, поле TcpTestSucceeded не единственное доступное для использования. Полезным может оказаться и поле PingSucceeded, указывающее на успешность пинга.

Единственное замечание по этим полям. При проверке портов, поле PingSucceeded всегда будет False. При выполнении командлета Test-NetConnection без параметра -Port, поле TcpTestSucceeded также, всегда будет равно False.

Итог

В статье было рассмотрено: Как выполнить проверку TCP-порта в PowerShell?

Содержание

Введение
Открытые порты
Проверить открыт ли порт
Открыть порт
Get-NetIPConfiguration: информация о сети
Разрешить RDP подключения
Статус OpenSSH сервера
Запустить sshd
hostname: Узнать имя хоста
Скачать файл
Похожие статьи

Введение

Это статья про работу с сетью в PowerShell

Изучить темы связанные с сетью в Windows вы можете

здесь

Общую информацию о сетях и протоколах можете найти в статье

«Компьютерные сети»

Открытые порты

Get-NetTcpConnection

Get-NetTcpConnection PowerShell изображение с сайта www.eth1.ru


Установка Ubuntu

Только порты, которые слушаются в данный момент

Get-NetTcpConnection -State Listen

Get-NetTcpConnection State Listen PowerShell изображение с сайта www.eth1.ru


Установка Ubuntu

Проверить открыт ли порт

Проверить открыт ли конкретный порт на удалённом хосте можно с помощью Test-NetConnection

Пример с портом 8080, открытым для

Jenkins

Test-NetConnection 10.30.200.116 -port 8080

ComputerName : 10.30.200.116
RemoteAddress : 10.30.200.116
RemotePort : 8080
InterfaceAlias : Ethernet 6
SourceAddress : 10.30.200.115
TcpTestSucceeded : True

Если порт закрыт

Test-NetConnection 10.30.200.116 -port 8082

WARNING: TCP connect to (10.30.200.116 : 8082) failed

ComputerName : 10.30.200.116
RemoteAddress : 10.30.200.116
RemotePort : 8082
InterfaceAlias : Ethernet 6
SourceAddress : 10.30.200.115
PingSucceeded : True
PingReplyDetails (RTT) : 5 ms
TcpTestSucceeded : False

РЕКЛАМА хостинга Beget, которым я пользуюсь более десяти лет

Изображение баннера

Конец рекламы хостинга Beget, который я всем рекомендую

Открыть порт

Чтобы открыть порт 22 для доступа по SSH выполните

New-NetFirewallRule -DisplayName «Allow SSH» -Profile «Private» -Direction Inbound -Action Allow -Protocol TCP -LocalPort 22

Открыть порт в PowerShell изображение с сайта www.eth1.ru


Установка Ubuntu

Получить информацию о сети

Ближайший аналог ipconfig из обычного cmd это Get-NetIPConfiguration

PS C:\Users\Andrei> Get-NetIPConfiguration

InterfaceAlias : vEthernet (Default Switch)
InterfaceIndex : 33
InterfaceDescription : Hyper-V Virtual Ethernet Adapter
IPv4Address : 172.24.128.1
IPv6DefaultGateway :
IPv4DefaultGateway :
DNSServer : fec0:0:0:ffff::1
fec0:0:0:ffff::2
fec0:0:0:ffff::3

InterfaceAlias : WiFi
InterfaceIndex : 8
InterfaceDescription : Intel(R) Dual Band Wireless-AC 8265
NetProfile.Name : Lester2.4G
IPv4Address : 192.168.0.105
IPv4DefaultGateway : 192.168.0.1
DNSServer : 192.168.0.1

InterfaceAlias : Bluetooth Network Connection
InterfaceIndex : 11
InterfaceDescription : Bluetooth Device (Personal Area Network)
NetAdapter.Status : Disconnected

InterfaceAlias : Local Area Connection
InterfaceIndex : 13
InterfaceDescription : TAP-ProtonVPN Windows Adapter V9
NetAdapter.Status : Disconnected

InterfaceAlias : Ethernet
InterfaceIndex : 4
InterfaceDescription : Intel(R) Ethernet Connection (4) I219-V
NetAdapter.Status : Disconnected

Разрешить RDP подключения

Set-ItemProperty -Path ‘HKLM:\System\CurrentControlSet\Control\Terminal Server’ -name «fDenyTSConnections» -value 0

Разрешить соединение в Firewall

Enable-NetFirewallRule -DisplayGroup «Remote Desktop»

Статус OpenSSH сервера

Проверить статус сервера

Get-Service sshd

Статус OpenSSH сервера в PowerShell изображение с сайта www.eth1.ru


Установка Ubuntu

Запустить OpenSSH сервер

Start-Service sshd

Get-Service sshd

Статус OpenSSH сервера в PowerShell изображение с сайта www.eth1.ru


Установка Ubuntu

hostname

Узнать имя хоста можно командой

hostname

Andrei0123

Скачать файл

Скачать файл можно командой Invoke-WebRequest.

Пример скрипта, который скачивает

thrift-0.19.0.exe

и сохраняет его как

thrift.exe

$THRIFT_URL = «https://dlcdn.apache.org/thrift/0.19.0/thrift-0.19.0.exe»

$FilePath = «.\thrift.exe»
If (Test-Path -path $FilePath -PathType Leaf) {
Write-Host «thrift.exe file exists» -f Green
} Else {
Write-Host «thrift.exe file does not exist — starting download» -f Yellow
Invoke-WebRequest $THRIFT_URL -OutFile thrift.exe
}

Автор статьи: Андрей Олегович

Похожие статьи

Windows
PowerShell
Посмотреть конец файла в PowerShell (аналог tail)
Создать новый файл в PowerShell (аналог touch)
Проверить контрольную сумму файла в PowerShell (аналог md5sum)

In PowerShell, you can test the connectivity of a TCP port using the `Test-NetConnection` cmdlet to check if a specific host is reachable on a given port.

Test-NetConnection -ComputerName "example.com" -Port 80

Understanding PowerShell and TCP Ports

TCP (Transmission Control Protocol) is one of the core protocols of the Internet Protocol Suite. It enables reliable communication between devices over a network by establishing connections that ensure data is transmitted without errors.

Ports are numerical identifiers in TCP that facilitate the routing of network traffic. Each application running on a device typically communicates over a specific port, making it crucial to test these ports when troubleshooting network issues or configuring servers.

PowerShell is a powerful command-line interface and scripting language that allows administrators to automate tasks and manage systems effectively. One of its many capabilities includes testing the connectivity of TCP ports.

PowerShell Test UDP Port: A Step-by-Step Guide

PowerShell Test UDP Port: A Step-by-Step Guide

Introduction to PowerShell Port Testing

Testing port connectivity is essential for various reasons, including ensuring that applications can communicate with each other, verifying firewall configurations, and troubleshooting issues related to network connectivity. Understanding how to effectively use PowerShell for these tasks can significantly streamline your administrative duties, making it a valuable skill for any IT professional.

Exploring PowerShell Test-Path for Quick File Checks

Exploring PowerShell Test-Path for Quick File Checks

PowerShell Commands for Port Testing

The `Test-NetConnection` Command

The `Test-NetConnection` cmdlet is one of the most versatile tools available in PowerShell for testing TCP connectivity. This command can check if a specific port on a remote server is open and accessible.

Syntax:

Test-NetConnection -ComputerName <hostname|IP> -Port <portnumber>

Example Usage:

To test whether port 80 (typically used for HTTP) is open on a website:

Test-NetConnection -ComputerName "example.com" -Port 80

The output will indicate whether the port is open, along with additional information about the connection.

The `Test-Connection` Command

While `Test-NetConnection` is specifically designed for testing TCP connectivity, the `Test-Connection` cmdlet is primarily used for checking ICMP (ping) connectivity.

Example Usage:

To check the connectivity without specifying the port, you would use:

Test-Connection -ComputerName "example.com"

This will return whether the host is reachable but does not provide information about specific ports.

The `tnc` Alias

PowerShell provides an alias, `tnc`, for the `Test-NetConnection` cmdlet to simplify the command-line syntax.

Example Usage:

Testing port 80 using the alias is as straightforward as:

tnc "example.com" -Port 80

This command behaves similarly to `Test-NetConnection` but is quicker to type as part of your daily tasks.

Checking Port Status

Detecting Open Ports

Identifying open ports is crucial for verifying that services are running as expected. When a port is open, it signifies that the application associated with it is listening for connections.

Example Command:

To check if port 443 (HTTPS) is open:

Test-NetConnection -ComputerName "example.com" -Port 443

Checking for Closed or Filtered Ports

If a port is closed or filtered, the output will provide this information, indicating a possible issue with the server or network configuration.

Example Command:

To test if port 25 (SMTP) is open or closed, use:

Test-NetConnection -ComputerName "example.com" -Port 25

The results will tell you if the connection was successful or not, providing context for troubleshooting.

PowerShell Test-NetConnection: A Quick Guide to Connectivity

PowerShell Test-NetConnection: A Quick Guide to Connectivity

Advanced TCP Port Testing Techniques

Using `Test-NetConnection` with Additional Parameters

`Test-NetConnection` offers a variety of parameters beyond just the computer name and port.

Example:

Getting a more detailed output when testing a connection can be accomplished with:

Test-NetConnection -ComputerName "example.com" -Port 80 -InformationLevel Detailed

This will provide extensive details about the connection attempt, including the underlying network conditions.

Diagnosing from Remote Locations

Sometimes, you may need to check ports across different remote servers. PowerShell Remoting is your friend here, allowing you to run commands on remote systems.

Example:

To check port connectivity from a remote server:

Invoke-Command -ComputerName "RemoteServer" -ScriptBlock { Test-NetConnection -ComputerName "example.com" -Port 80 }

This command will execute the port test on the specified remote server.

Mastering PowerShell: How to Stop a Process Effortlessly

Mastering PowerShell: How to Stop a Process Effortlessly

Practical Applications

Troubleshooting Common Networking Issues

PowerShell commands for port testing can play a crucial role in diagnosing various connectivity issues. For instance, if a web application is not functioning properly, a quick check of the relevant TCP ports can determine if the required services are up and running.

Port Testing in Automation Scripts

You can integrate these commands into your automation scripts to regularly monitor the status of key services. This proactive approach ensures you catch issues early on.

Example Script Snippet:

Here’s how you could test multiple servers to check port 80:

$servers = @("server1", "server2", "server3")
foreach ($server in $servers) {
    tnc $server -Port 80
}

This script iterates through a list of servers and checks the specified port, providing ongoing visibility into server health.

Powershell Get Certificate: A Quick Guide to Mastery

Powershell Get Certificate: A Quick Guide to Mastery

Conclusion

In summary, understanding how to effectively utilize PowerShell to test TCP ports empowers you to troubleshoot connectivity issues and ensure that your applications and services are accessible as intended. The commands discussed, including `Test-NetConnection`, `Test-Connection`, and the `tnc` alias, equip you with the tools needed for robust network management.

PowerShell List Certificates: A Quick Guide

PowerShell List Certificates: A Quick Guide

Additional Resources

For those looking to deepen their understanding of network diagnostics in PowerShell, consult the official Microsoft documentation or consider additional training materials dedicated to PowerShell scripting and networking functions.

PowerShell Restart Process: Simple Steps to Master It

PowerShell Restart Process: Simple Steps to Master It

FAQs

What is the difference between `Test-NetConnection` and `Test-Connection`?

`Test-NetConnection` is specialized for testing TCP connections to specific ports, while `Test-Connection` is optimized for pinging hosts using ICMP packets.

Can I test multiple ports at once with PowerShell?

You can run a loop to check multiple ports or integrate it into an automated script to check an array of ports across different hosts.

What will the output of the `Test-NetConnection` command look like?

The output includes the result of the connection attempt, the IP address resolved, and additional information about the network path.

Are there any limitations to using PowerShell for port testing?

While PowerShell is powerful, port testing can be affected by firewall settings, network restrictions, or insufficient permissions on the targeted servers, which might limit your ability to gather accurate results.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Qualcomm atheros ar3012 driver windows 10
  • 0xe0000100 при установке обновления windows 10
  • Как создать флешку для установки windows 10 через rufus
  • Zyxel drive для windows
  • Acronis как удалить windows