You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PowerShell从文件读取双变量并执行Ping测试?

PowerShell读取文件批量执行Ping测试的实现方法

实现步骤与代码

  1. 读取并分组文件内容
    先将file01.txt的内容按空行分割,把每组server和IP的信息单独提取出来:

    # 读取文件并按空行分割为服务器信息组,过滤空内容
    $serverGroups = (Get-Content -Path "file01.txt" -Raw) -split "`n`n" | Where-Object { $_ -match '\S' }
    
  2. 遍历每组执行Ping测试
    循环处理每个服务器组,提取server名称和IP地址,然后执行Ping测试并输出结果:

    foreach ($group in $serverGroups) {
        # 提取server名称
        $server = ($group | Select-String 'server: (.*)').Matches.Groups[1].Value
        # 提取IP地址
        $ip = ($group | Select-String 'IP: (.*)').Matches.Groups[1].Value
    
        # 输出测试提示
        Write-Host "正在测试: $server ($ip)" -ForegroundColor Cyan
        # 执行Ping测试,2次尝试,返回布尔结果
        $isReachable = Test-Connection -ComputerName $ip -Count 2 -Quiet -ErrorAction SilentlyContinue
    
        # 根据结果输出不同颜色的提示
        if ($isReachable) {
            Write-Host "$server ($ip) 连通正常" -ForegroundColor Green
        } else {
            Write-Host "$server ($ip) 无法连通" -ForegroundColor Red
        }
        Write-Host "-------------------------"
    }
    

代码说明

  • Get-Content -Raw:一次性读取整个文件为字符串,便于按空行分割分组
  • -split "nn":将文件内容按连续换行(空行)分割成独立的服务器信息组
  • Select-String:通过正则表达式匹配提取server和IP的具体值
  • Test-Connection:PowerShell内置的Ping测试命令,-Quiet参数直接返回连通状态的布尔值,-Count指定测试次数,-ErrorAction SilentlyContinue避免因无法连通抛出冗余错误
  • 彩色输出:用ForegroundColor区分不同状态的结果,更易查看

内容的提问来源于stack exchange,提问作者debug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:01:02