djsnakz
djsnakz

Reputation: 478

PowerShell Mass Test-Connection

I am attempting to put together a simple script that will check the status of a very large list of servers. in this case we'll call it servers.txt. I know with Test-Connection the minimum amount of time you can specify on the -count switch is 1. my problem with this is if you ended up having 1000 machines in the script you could expect a 1000 second delay in returning the results. My Question: Is there a way to test a very large list of machines against test-connection in a speedy fashion, without waiting for each to fail one at a time?

current code:

Get-Content -path C:\Utilities\servers.txt | foreach-object {new-object psobject -property @{ComputerName=$_; Reachable=(test-connection -computername $_ -quiet -count 1)} } | ft -AutoSize 

Upvotes: 6

Views: 12446

Answers (3)

Ori Besser
Ori Besser

Reputation: 81

Powershell 7 and Foreach-Object -Parallel makes it much simpler now:

Get-Content -path C:\Utilities\servers.txt | ForEach-Object -Parallel {
    Test-Connection $_ -Count 1 -TimeoutSeconds 1 -ErrorAction SilentlyContinue -ErrorVariable e
    if ($e)
    {
        [PSCustomObject]@{ Destination = $_; Status = $e.Exception.Message }
    }
} | Group-Object Destination | Select-Object Name, @{n = 'Status'; e = { $_.Group.Status } }

Upvotes: 2

Anders Wahlqvist
Anders Wahlqvist

Reputation: 106

Test-Connection has a -AsJob switch which does what you want. To achieve the same thing with that you can try:

Get-Content -path C:\Utilities\servers.txt | ForEach-Object { Test-Connection -ComputerName $_ -Count 1 -AsJob } | Get-Job | Receive-Job -Wait | Select-Object @{Name='ComputerName';Expression={$_.Address}},@{Name='Reachable';Expression={if ($_.StatusCode -eq 0) { $true } else { $false }}} | ft -AutoSize

Hope that helps!

Upvotes: 9

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58491

I have been using workflows for that. Using jobs spawned to many child processes to be usable (for me).

workflow Test-WFConnection {
  param(
    [string[]]$computers
  )
    foreach -parallel ($computer in $computers) {        
        Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
  }
}

used as

Test-WFConnection -Computers "ip1", "ip2"

or alternatively, declare a [string[]]$computers = @(), fill it with your list and pass that to the function.

Upvotes: 6

Related Questions