TAGS :Viewed: 3 - Published at: a few seconds ago

[ How to clear only certain contents from the screen? ]

Function Test{
    while($true){
    write-host "I want this to refresh every time"
    Start-Sleep -Seconds 4
    cls
    }
}
Write-Host "I want this to be at the screen always"
Test

Is there a way for me to get this done other than putting it also inside the loop or function ? In the actual code I want to keep some output at the top of the screen for reference(it cannot be put inside the function), while the function pulls some data and refresh every 4 seconds. Here since I use cls it clears everything on the screen which I do not want to happen. I only needs to clear the output from the function.

Answer 1


Would a progress bar be suitable? The actual percentage may not be relevant because the loop in the example is infinite, but it does behave similar to what you describe:

Function Test{
   while ($true) {
      Write-Progress -Activity "I want this to be at the screen always" -Status "I want this to refresh every time"
      Start-Sleep -Seconds 4
   }
}
Write-Progress -Activity "I want this to be at the screen always"
Test

Answer 2


If Write-Progress is not suitable then a function using global variables might work for you:

Function Clear-HostCustom ($DisplayText)
{
    If ($DisplayText)
    {
        $global:DisplayTextGlobal = $DisplayText
    }
    Clear-Host
    Write-Host $global:DisplayTextGlobal
}
Function Test{
    while($true){
    write-host "I want this to refresh every time"
    Start-Sleep -Seconds 4
    Clear-HostCustom
    Start-Sleep -Seconds 1
    }
}
Clear-HostCustom "I want this to be at the screen always"
Test