Overwriting Format-Table with PowerShell

Jason Crawford
Jason Crawford used Ask the Experts™
on
I'm attempting to send the output of a while loop to a table that overwrites itself in the console upon each iteration of the loop.  Here is the script so far:

$array = @(
  'google.com'
  'yahoo.com'
  'reddit.com'
)

While ($true) {
  foreach ($Server in $Array) {
    $ping  = Test-Connection $server -Count 1
    if (!($ping)) {
      $status = 'Down'
    }
    else {
      $status = 'Up'
    }
    
    [array]$results += New-Object -TypeName PSObject -Property @{
      'Device Name' = $server
      'Status' = $status
      'IP Address'       = $ping.IPV4Address
      'Response Time' = $ping.ResponseTime
      }
    }
$results | Format-Table -AutoSize
}

Open in new window

The problem is the output isn't overwriting anything it is adding onto.  I realize this is because of the += used for the $results variable, I'm just not sure what to do about it.  Help?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Reset $results to $null at the start of the foreach loop:
While ($true) {
  $results = $null
  foreach ($Server in $Array) {
  

Open in new window

And maybe a
Clear-Host
is required right before the $results | Format-Table -AutoSize

Clear-Host 
$results | Format-Table -AutoSize

Open in new window

Or, to reduce flicker, use setcursorposition

[console]::setcursorposition(0,0)

$array = @(
  'google.com'
  'yahoo.com'
  'reddit.com'
)
Clear-Host 
While ($true) {
  $results = $null
  foreach ($Server in $Array) {
    $ping  = Test-Connection $server -Count 1
    if (!($ping)) {
      $status = 'Down'
    }
    else {
      $status = 'Up'
    }
    
    [array]$results += New-Object -TypeName PSObject -Property @{
      'Device Name' = $server
      'Status' = $status
      'IP Address'       = $ping.IPV4Address
      'Response Time' = $ping.ResponseTime
      }
    }
[console]::setcursorposition(0,0) 
$results | Format-Table -AutoSize
}

Open in new window

Author

Commented:
Wow...I need sleep.  Thank you.
Start-Sleep $now for(at least 8h) ;-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial