惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
博客园_首页
Google DeepMind News
Google DeepMind News
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Recent Announcements
Recent Announcements
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
量子位
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
有赞技术团队
有赞技术团队
Jina AI
Jina AI
GbyAI
GbyAI

wentao's blog

解决armbian更新报不能验证个别公钥 nyagos增加zoxide的支持 快速查找PowerShell的历史命令 denote wezterm的workspace配置 PSReadLine最强PowerShell模块 读《万千微尘纷坠心田》 Emacs添加腾讯会议连接 一个新的终端模拟器WezTerm
利用PowerShell来进行端口连通性测试
wentao写点代码,解决点问题。 douban github twitter Spotify telegram · 2022-07-17 · via wentao's blog

一般情况下在是使用 telnet 来做网络连通性的测试. PowerShell 也可以实现类似的功能.而且由于本身和 .Net 的关系,还可以通过 .Net 的支持来完成.

原生的方案:Test-Connection

连接成功

Measure-Command {Test-NetConnection wentao.org -Port 80} | % TotalSeconds

连接失败

Measure-Command {Test-NetConnection wentao.2org -Port 80} | % TotalSeconds

使用System.Net.Sockets.TcpClient的方案

  function Test-Port {
	[CmdletBinding()]
	param (
		[Parameter(ValueFromPipeline = $true, HelpMessage = 'Could be suffixed by :Port')]
		[String[]]$ComputerName,

		[Parameter(HelpMessage = 'Will be ignored if the port is given in the param ComputerName')]
		[Int]$Port = 5985,

		[Parameter(HelpMessage = 'Timeout in millisecond. Increase the value if you want to test Internet resources.')]
		[Int]$Timeout = 1000
	)

	begin {
		$result = [System.Collections.ArrayList]::new()
	}

	process {
		foreach ($originalComputerName in $ComputerName) {
			$remoteInfo = $originalComputerName.Split(":")
			if ($remoteInfo.count -eq 1) {
				# In case $ComputerName in the form of 'host'
				$remoteHostname = $originalComputerName
				$remotePort = $Port
			} elseif ($remoteInfo.count -eq 2) {
				# In case $ComputerName in the form of 'host:port',
				# we often get host and port to check in this form.
				$remoteHostname = $remoteInfo[0]
				$remotePort = $remoteInfo[1]
			} else {
				$msg = "Got unknown format for the parameter ComputerName: " `
					+ "[$originalComputerName]. " `
					+ "The allowed formats is [hostname] or [hostname:port]."
				Write-Error $msg
				return
			}

			$tcpClient = New-Object System.Net.Sockets.TcpClient
			$portOpened = $tcpClient.ConnectAsync($remoteHostname, $remotePort).Wait($Timeout)

			$null = $result.Add([PSCustomObject]@{
				RemoteHostname       = $remoteHostname
				RemotePort           = $remotePort
				PortOpened           = $portOpened
				TimeoutInMillisecond = $Timeout
				SourceHostname       = $env:COMPUTERNAME
				OriginalComputerName = $originalComputerName
				})
		}
	}

	end {
		return $result
	}
}