Public/Ping-AllHosts.ps1

Function Ping-AllHosts {
  <#
      .SYNOPSIS
      Will ping all entries in your HOSTS file (C:\WINDOWS\System32\drivers\etc\hosts) very quickly.
 
      .EXAMPLE
      PS C:\> Ping-AllHosts -Count 30
 
      Will ping all hosts a total of 30 times, pausing for the default 10 seconds inbetween iterations.
      .EXAMPLE
      PS C:\> Ping-AllHosts -t -DelayMS 30000
 
      Will continue to ping hosts waiting 30 seconds inbetween iterations.
      .EXAMPLE
      PS C:\> Ping-AllHosts -Count 10
 
      Will ping all hosts a total of 10 times.
      .NOTES
      Name: Ping-AllHosts
      Author: Tyson Paul
      Blog: https://monitoringguys.com/
      Date: 2018.04.30
      History: v1.0
 
  #>


  Param (
    [long]$Count=1,
    [long]$DelayMS=10000,
    [switch]$t
  )

  $HOSTSfile = (Join-Path $env:SystemRoot '\System32\drivers\etc\hosts')
  If (-NOT (Test-Path $HOSTSfile -PathType Leaf) ) {
    Write-Error "Cannot find 'hosts' file at: $HOSTSFile . Exiting."
    Return
  }
  If ($t) {
    $Count = 9999999999999
    Write-Host "`$Count = $Count" -ForegroundColor Yellow

  }
  [long]$i=1
  While ($i -le $Count) {
    Write-Host "Attempt: $i. Remaining attempts: $($Count - $i)" -F Green
    # Parse the Hosts file, extract only the lines that do NOT begin with hash (#). Discard any leading tabs or spaces on all lines. Ignore blank lines
    $lines = (( (Get-Content $HOSTSfile).Replace("`t",'#').Replace(" ",'#').Replace("##",'#') | Where-Object {$_ -match '^[^#]'}))  | Where-Object {$_.Length -gt 1}

    $hash = @{}
    # Assign names and IPs to hash table
    $lines | ForEach-Object { $hash[$_.Split('#')[1]] = $_.Split('#')[0] }
    If (-Not [bool]$lines) {
      Write-Host "No valid hosts found in file. Exiting."
      Return
    }
    # Perform simultaneous address connection testing, as job.
    $job = Test-Connection -ComputerName ($hash.Keys | Out-String -stream) -Count 1 -AsJob

    Do{
      Write-Host 'Waiting for ping test to complete...' -F Yellow
      Start-Sleep 3

    }While($job.JobStateInfo.State -eq "Running")
    Receive-Job $job |
    Select-Object @{N="Source"; E={$_.PSComputerName}},
    @{N="Target"; E={$_.Address}},
    IPV4Address,
    @{N='Time(ms)';E={($_.'ResponseTime')} },
    @{N='Alive?';E={([bool]$_.'ResponseTime')} } |
    Sort-Object Target |
    Format-Table -AutoSize

    If ($i -eq $Count) {Return}
    $i++
    Write-Host "Sleeping $($DelayMS / 1000) Seconds before next ping test..."
    Start-Sleep -Milliseconds $DelayMS
  }
}