首页 > 解决方案 > 需要帮助将 ping 结果写入分离文件以供上下机器使用

问题描述

我需要 ping 一个机器列表,并将结果分成上下两个不同的 .txt 文件。

$PingPCs = Get-Content "C:\Temp\Cache Cleanup Project\Computerlist.txt
foreach ($PC in $PingPCs) {
        $up = Test-Connection $PC -Count 1 -Quiet
        if($up) {
                  $Response = Test-Connection $PC -Count 1 | Select-Object Name
                  $Response ## Need help figuring out the outfile process to write to .txt ##
        }
        else {
              $Failed = "$PC is not reachable"
              $Failed ### Need help figuring out the outfile process to write to .txt ###
        }
}

我需要帮助的两个地方只是将结果写入单独的文本文件。一个名为 Online.txt 的文件和另一个名为 Offline.txt 的文件。

标签: powershell

解决方案


您可以这样做,而不是在每次迭代中导出结果并附加到文件中,最好先执行测试并将结果保存在内存中。全部完成后,导出结果:

$PingPCs = Get-Content "C:\Temp\Cache Cleanup Project\Computerlist.txt"

$result = foreach ($PC in $PingPCs)
{
    $testConnection = Test-Connection $PC -Count 1 -Quiet

    [pscustomobject]@{
        ComputerName = $PC
        TestConnection = $testConnection
    }
}

$result.where({$_.TestConnection}) | Out-File "x:\path\to\online.txt"
$result.where({-not $_.TestConnection}) | Out-File "x:\path\to\offline.txt"

编辑

添加很好的优化以导出结果。谢谢@mklement0

$online, $offline = $result.where({$_.TestConnection},'Split')
$online | Out-File "x:\path\to\online.txt"
$offline | Out-File "x:\path\to\offline.txt"

推荐阅读