Philly
Philly

Reputation: 81

Test-Connection Performance Slow

I have a list of devices that I would like to ping against to see if they are active or not. If they are active (even if not), I would like to log to a file. So, the active devices go to one file, and the "unpingable" devices are written to another file. The script I have below works okay for a smaller sampling of computers, but when I add the complete list, the "test-connection" section of the script takes hours to complete (about 8,000 devices). Is there a way to improve the performance by running the command in parallel? In my search, i came across this wrapper function by David Wyatt => TestConnectionAsync but I'm unsure how to make it work with separating results in two files. Any help would be appreciated.

Code:

ForEach ($PC in $Computer_List) {
  If (Test-Connection -ComputerName $PC -Quiet -Count 1) {
    Add-Content -value $PC -Path "$UPpath"
  } Else {
    Add-Content -Value $PC -Path "$DOWNpath"
  }
}

Upvotes: 1

Views: 963

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

The output from Test-ConnectionAsync makes this quite easy:

When you specify the -Quiet switch of Test-ConnectionAsync, it returns a collection of PSCustomObjects with the properties "ComputerName" and "Success". Success is the boolean value you'd have received from Test-Connection -Quiet ; the PSCustomObject just allows you to associate that result with the target address.

So all you've got to do is:

  1. Ping all computers and capture the output
  2. Look at the Success attribute to see if you should put it in one file or another

# 1. Gather ping results
$TestResults = $ComputerList | Test-ConnectionAsync -Quiet

# 2. Loop through results and look at Success
foreach($Result in $TestResults){
    $FilePath = if($Result.Success){
        $UPpath
    } else {
        $DOWNpath
    }
    Add-Content -Path $FilePath -Value $Result.ComputerName
}

Upvotes: 2

Related Questions