Doing Things Forever

by Mar 9, 2016

If you want PowerShell to run forever, for example in order to continuously ping a site, use a simple endless loop:

#requires -Version 2

$ComputerName = 'powershellmagazine.com'

$status = @{
  $true = 'is online.'
  $false = 'cannot be reached.'
}

do
{
  $date = Get-Date -Format 'HH:mm:ss'
  
  $online = Test-Connection -ComputerName $ComputerName -Quiet -Count 1
  $text = $status.$online
  
  "$date : $ComputerName $text"
  
  Start-Sleep -Milliseconds 2000
} while ($true)

Note how the sample code uses Test-Connection to ping a computer. Also, note how a hash table ($status) is used to turn the Boolean value returned by Test-Connection into a text.

Twitter This Tip! ReTweet this Tip!