Test netconnection не распознано как имя командлета
Перейти к содержимому

Test netconnection не распознано как имя командлета

  • автор:

Test netconnection не распознано как имя командлета

date08.06.2022
useritpro
directoryPowerShell
commentsкомментариев 5

Test-NetConnection cmdlet is missing from PowerShell Core 6.0.1 release #6932

Test-Connection was added in 5328 but it appears that Test-NetConnection is still missing.

Steps to reproduce

Expected behavior

Actual behavior

Environment data

The text was updated successfully, but these errors were encountered:

I’m a little unclear, does that mean that Powershell 6 will not have Test-NetConnection? I would expect the ability to check a specific port on a system would be of even more interest to unix admins.

My assumption was that, like Test-Connection, Test-NetConnection had also been overlooked. If that was an incorrect assumption, then perhaps this should be re-labeled as a feature request. Otherwise, I believe this is a bug.

@kevinlrak Current Test-Connection ported implementation was enhanced. Please see help Test-Connection .

You can to check a specific port too.
.Net Core has still bugs in APIs and not all in Test-Connection works on Unix.
Feel free to test and feedback.

Nettcpip module is not in the repo (another MSFT team is owner) and it is not ported.

@iSazonov what version are you running? I’m on the 6.1.0-preview.2, but my help Test-Connection does not match what you put above. Neither does the online help page for Test-Connection in Powershell 6.

Here is what I get:

However, when I try running Test-Connection with the -TCPPort flag, it does seem to function. So I believe this is mostly a problem with that enhancement being undocumented in the latest current release (6.1.0-preview.2)

@kevinlrak It is a trick 🙂 or bug. You catch Windows PowerShell help. You can find where it is by:

After I rename folder C:\Users\sie\Documents\PowerShell\Help I get the right help.

In PowerShell 6.0.2, version installed through HomeBrew on a Mac, both commands are missing:

  • Get-Command : The term ‘Test-NetConnection’ is not recognized as the name of a cmdlet [. ]
  • get-Command : The term ‘Test-Connection’ is not recognized as the name of a cmdlet [. ]

@corretge You’ll get Test-Connection in 6.1 version or you can use 6.1 Preview2 or current dev builds.

In my eyes this is breaking all compatibility with no understand from my side, why not implement Test-NetConnection.
It would be really wise to implement it .
This is again one of the commands where I have if/else for what it is running on. and worse enough, it has to be a check for 5.1/7.x, Windows/Linux (5.1 does not support -TCPPort, Linux does not support Test-NetConnection)
is this the type of Multi-Plattform-Support Microsoft is aiming at?
Please reconsider this, as it really breaks scripts that do network checks and should run on multiple plattforms or be easy to port.

I just came across this today and could really use Test-NetConnection in pwsh on Mac!

See above; you should be able to use Test-Connection for most of the use cases that Test-NetConnection covered in earlier versions. If you have a specific use case that the current implementation doesn’t cover, I suggest you open a feature / improvement request for that cmdlet instead. ��

@vexx32 But as said above. This breaks scripts to be compatible on multiple plattforms. And that because of a really bad reason, in my eyes, as Test-NetConnection could be easily built as the functionality is present in parts in test-connection.

I have to disagree, since I wrote quite a lot of the current implementation of Test-Connection. Many of the features Test-NetConnection had are simply not available in .NET itself currently. Even the things that are there largely only work on Windows, from what I’ve been able to determine.

It’s probably possible with a third-party library, but I’m not familiar enough in that area to know what would be useful to look at, nor would I expect the maintainers to want to pull it in as a permanent dependency.

Test-NetConnection is simply not cross-platform compatible; some of the things it does on WIndows simply don’t have direct analogues on other platforms, as far as I am able to tell. Test-Connection is, to the best of our current ability, the closest we have and is available even back in WinPS 5.1 (with some minor differences from the current implementation; it too had to be rewritten completely, in the end).

If you’d like to expand what it can do, feel free; I have no doubt that useful functionality would likely be welcomed as a PR. ��

Test-NetConnection: термин «Test-NetConnection» не распознается как имя командлета, функции, файла сценария или исполняемой программы.

Я хотел бы подключиться к общей папке с лазурного портала на моем ноутбуке с Windows. Однако соответствующая ошибка показана ниже.

Ошибка: Test-NetConnection: термин «Test-NetConnection» не распознается как имя командлета, функции, файла сценария или исполняемой программы. Проверьте правильность написания имени или, если был указан путь, убедитесь, что путь указан правильно, и повторите попытку.

Test-NetConnection: проверка открытых/закрытых TCP портов из PowerShell

date08.06.2022
useritpro
directoryPowerShell
commentsкомментариев 6

В PowerShell 4.0 (Windows 2012 R2, Windows 8.1 и выше) появился встроенный командлет для проверки сетевых соединений — Test-NetConnection. С помощью данного командлета вы можете проверить доступность удаленного сервера или сетевой службы на нем, блокировку TCP портов файерволами, проверить доступность по ICMP и маршрутизацию. По сути, командлет Test-NetConnection позволяет заменить сразу несколько привычных сетевых утилит: ping, traceroute, сканер TCP портов и т.д.

Основное преимущество командлета Test-NetConnection – он уже входит в состав всех современных версий Windows и вам не нужно устанавливать его отдельно. Командлет входит в состав модуля NetTCPIP (начиная с PoSh v4.0).

$PSVersionTable.PSVersion

Значение 4 в столбце Major говорит о том, что на компьютере установлен PowerShell 4.0.

TCP Port Ping: Использование Test-NetConnection для проверки открытых портов и доступности серверов

Проверим, открыт ли порт TCP 25 (SMTP протокол) на почтовом сервере с помощью Test-NetConnection:

Test-NetConnection -ComputerName msk-msg01 -Port 25

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

TNC msk-mail1 -Port 25

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

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

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

У командлета есть специальный параметр –CommonTCPPort, позволяющий указать наименование известного сетевого протокола (HTTP, RDP, SMB, WINRM).

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

Test-NetConnection -ComputerName winitpro.ru -CommonTCPPort HTTP

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

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

New-Object System.Net.Sockets.TcpClient

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

Test-NetConnection msk-man01 –TraceRoute

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

Test-NetConnection TraceRoute

Test-NetConnection в скриптах мониторинга

Следующая команда позволить проверить доступность определенного порта на множестве серверов, список которых хранится в текстовом файле servers.txt. Нас интересуют сервера, где искомая служба не отвечает:

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

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

  • RPC – TCP/135
  • LDAP – TCP/389
  • LDAP – TCP/3268
  • DNS – TCP/53

$Ports = «135»,»389″,»636″,»3268″,»53″,»88″,»445″,»3269″, «80», «443»
$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address,isGlobalCatalog,Site,Forest,OperatingSystem
ForEach($DC in $AllDCs)
<
Foreach ($P in $Ports)<
$check=Test-NetConnection $DC -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)

else

>

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

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

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

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *