PowerShell Mass Test-Connection

前端 未结 3 809
野趣味
野趣味 2021-01-05 12:34

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

相关标签:
3条回答
  • 2021-01-05 13:12

    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 } }
    
    0 讨论(0)
  • 2021-01-05 13:14

    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!

    0 讨论(0)
  • 2021-01-05 13:23

    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.

    0 讨论(0)
提交回复
热议问题