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

}

}

}

相关推荐
waterHBO几秒前
css 模拟一个动画效果,消息堆叠。
前端·css
小七rrrrr10 分钟前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
前端加油站16 分钟前
在 cursor 成为流行的开发方式后,作为普通开发我们能做什么
前端
自由的疯18 分钟前
在 Java IDEA 中使用 DeepSeek 详解
java·后端·架构
忧郁的橙子.20 分钟前
三、k8s 1.29 之 安装2
linux·运维·服务器
自由的疯24 分钟前
Java 通过接口方式使用 DeepSeek 详解
java·后端·trae
Cache技术分享24 分钟前
163. Java Lambda 表达式 - Function 的链式组合
前端·后端
敲代码中32 分钟前
Maven入门到精通
java·maven
Zestia41 分钟前
页面点击跳转源代码?——element-jumper插件实现
前端·javascript