简体   繁体   中英

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 

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM