PowerShell – How to See When a Ping Was Lost or Not Answered

powershellwindows

When I install Windows updates, or perform other maintenance that at some point involves one or more automatic reboots, I've had the same challenge over and over again for years:

  1. How can I check if the network connection to a specific device was interrupted and how can I log this with timecode? Even if the interruption lasted only a few seconds, as is common when rebooting a VM.

  2. How can I find out when and how long the network connection interruption (= reboot) occurred without a long search in logfiles?

  3. Is there any way to solve this challenge without special software? Only with Windows tools like PowerShell?

Best Answer

I typically use this script to watch one or more computers going up and down.

# pinger.ps1

# example: pinger comp01
# pinger $list

param ($hostnames)

$pingcmd = 'test-connection'

$sleeptime = 1

$sawup = @{}
$sawdown = @{}

foreach ($hostname in $hostnames) { 
  $sawup[$hostname] = $false
  $sawdown[$hostname] = $false
}

while ($true) {
  foreach ($hostname in $hostnames) {
    if (& $pingcmd -count 1 $hostname -ea 0) {
      if (! $sawup[$hostname]) {
        echo "$([console]::beep(500,300))$hostname is up $(get-date)"
        $sawup[$hostname] = $true
        $sawdown[$hostname] = $false
      }
    } else {
      if (! $sawdown[$hostname]) {
        echo "$([console]::beep(500,300))$hostname is down $(get-date)"
date}
        $sawdown[$hostname] = $true
        $sawup[$hostname] = $false
      }
    }
  }
  sleep $sleeptime
}
pinger comp01,comp02

comp01 is up 12/02/2022 13:16:47
comp02 is up 12/02/2022 13:16:47