Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Mass Test-Connection

Tags:

powershell

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 
like image 580
djsnakz Avatar asked May 06 '15 05:05

djsnakz


People also ask

How do I do a test-connection in PowerShell?

PowerShell Test-Connection Just like ping, uses Test-Connection also the ICMP protocol to test the network connectivity of a network device. In the simplest form, you can type Test-Connection <computername> or <ip-address> to do a quick connectivity test.

How do I check ping for multiple servers in PowerShell?

You need to use the PowerShell ping command to test for echo or response from the computer. If you want to check multiple computers active status if they are online or offline, using PowerShell test-connection cmdlet, it is easily determined if the list of computers is reachable or not.

How can I tell if my ping is successful in PowerShell?

The Test-Connection cmdlet pings the Server01 computer, with the Quiet parameter provided. The resulting value is $True if any of the four pings succeed. If none of the pings succeed, the value is $False .


2 Answers

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!

like image 145
Anders Wahlqvist Avatar answered Nov 15 '22 07:11

Anders Wahlqvist


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.

like image 33
Lieven Keersmaekers Avatar answered Nov 15 '22 06:11

Lieven Keersmaekers