Need help writing ping results to separate files for up and down machines

Viewed 54

I need to ping a list of machines and have the results split between up and down into two different .txt files.

$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 ###
        }
}

The two places I need help with is just writing the results to separate text files. One file named Online.txt and the other Offline.txt.

1 Answers

You can do something like this, instead of exporting the results on each iteration and appending to a file, it's a better idea to first perform your test and save the results in memory. Once all is complete, export the results:

$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"

Edit

Adding nice optimization to export the results. Thanks @mklement0

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