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 location inside the console window. To set the caret to the top left corner, for example, use this:

$esc = [char]27
$setCursorTop = "$esc[0;0H"

Write-Host "${setCursorTop}This always appears in line 0 and column 0!"

When you run this, the text is always located in line 0 and column 0. You can use this technique to create your own custom progress indicator – just remember: all of this works in console windows, only, not in the PowerShell ISE.

function Show-CustomProgress
{
    try
    {
        $esc = [char]27
    
        # let the caret move to column (horizontal) pos 12
        $column = 12
        $resetHorizontalPos = "$esc[${column}G"
        $gotoFirstColumn = "$esc[0G"
        
        $hideCursor = "$esc[?25l"
        $showCursor = "$esc[?25h"
        $resetAll = "$esc[0m" 

        # write the template text
        Write-Host "${hideCursor}Processing     %." -NoNewline

        1..100 | ForEach-Object {
            # insert the current percentage
            Write-Host "$resetHorizontalPos$_" -NoNewline
            Start-Sleep -Milliseconds 100
        }
    }
    finally
    {
        # reset display
        Write-Host "${gotoFirstColumn}Done.              $resetAll$showCursor"
    }
}

When you run this code, then enter the command Show-CustomProgress, you’ll see an incrementing custom progress indicator. The console hides the blinking prompt. When the indicator is done, or when you press CTRL+C, the progress indicator hides, and instead the word “Done.” appears. The caret starts blinking again.

Twitter This Tip! ReTweet this Tip!

Anonymous