Starting in PowerShell 5.1, the PowerShell console supports VT escape sequences that can be used to position and format console text. Note that this works in the console only, not the PowerShell ISE. Note also that you either need Windows 10 or an emulator like ConEmu.

VT escape sequences can set the console cursor to any position inside the current line. This way, you can easily create a function that outputs status or log messages to the console, and instead of adding new lines with each message, overwrite the previous message.

function Write-ConsoleMessage([string]$Message)
{
    $esc = [char]27
    $consoleWidth = [Console]::BufferWidth
    $outputText = $Message.PadRight($consoleWidth)
    $gotoFirstColumn = "$esc[0G"
    Write-Host "$gotoFirstColumn$outputText" -NoNewline
}

function test
{
    Write-ConsoleMessage -Message 'Starting...'
    Start-Sleep -Seconds 1
    Write-ConsoleMessage -Message 'Doing something!'
    Start-Sleep -Seconds 1
    Write-ConsoleMessage -Message 'OK.'
}

test

Twitter This Tip! ReTweet this Tip!

Anonymous