powershell 批量测试ip 端口 脚本

方案1

定义IP地址和端口列表

$ips = @(

"192.168.1.75",

"192.168.1.76",

)

$ports = @(1433,80)

$timeout = 500 # 毫秒

创建结果数组

$results = @()

foreach (ip in ips) {

foreach (port in ports) {

try {

$client = New-Object System.Net.Sockets.TcpClient

connect = client.BeginConnect(ip, port, null, null)

wait = connect.AsyncWaitHandle.WaitOne($timeout) # 等待连接,超时为500毫秒

if ($wait) {

client.EndConnect(connect) # 完成连接

$status = "Open"

} else {

$status = "Timeout" # 超时视为关闭或不可达

}

$client.Close() # 关闭客户端连接

$results += [PSCustomObject]@{

IP = $ip

Port = $port

Status = $status

}

} catch {

$results += [PSCustomObject]@{

IP = $ip

Port = $port

Status = "Error"

ErrorMessage = $_.Exception.Message

}

}

}

}

输出结果

$results | Format-Table -AutoSize

方案2

$computers = "192.168.1.75 # 要测试的计算机列表

$ports = "1433" # 要测试的端口列表

foreach (computer in computers) {

foreach (port in ports) {

result = Test-NetConnection -ComputerName computer -Port $port -InformationLevel Quiet

if (result -eq true) {

Write-Host "computer : Port port is open" -ForegroundColor Green

} else {

Write-Host "computer : Port port is closed" -ForegroundColor Red

}

}

}

相关推荐
hpoenixf4 小时前
2026 年前端面试问什么
前端·面试
还是大剑师兰特4 小时前
Vue3 中的 defineExpose 完全指南
前端·javascript·vue.js
疯狂吧小飞牛4 小时前
GPG基础指令
linux·服务器·网络
C++ 老炮儿的技术栈4 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
泯泷4 小时前
阶段一:从 0 看懂 JSVMP 架构,先在脑子里搭出一台最小 JSVM
前端·javascript·架构
大阿明4 小时前
Spring Boot(快速上手)
java·spring boot·后端
bearpping5 小时前
Java进阶,时间与日期,包装类,正则表达式
java
邵奈一5 小时前
清明纪念·时光信笺——项目运行指南
java·实战·项目
hjxu20165 小时前
【OpenClaw 龙虾养成笔记一】在远程服务器,使用Docker安装OpenClaw
服务器·笔记·docker
mengchanmian5 小时前
前端node常用配置
前端