PowerShell Tip: Another Take On Progress Reporting

Normally in PowerShell if you want to report progress on a long running task, you’d use a progress bar using the Write-Progress cmdlet. That’s definitely the right way to do this, but what if you wanted a different way… for some reason? In the PowerShell Slack (invite yourself: slack.poshcode.org), I recently answered this question: “I want to write out ‘There are 3 seconds remaining. There are 2 seconds remaining.’ etc. until there are no seconds remaining and then keep going, but I don’t want them all to appear on the different lines. I basically just want the number to update.”

This gif shows what the question asker was after (except instead of counting up, they wanted a countdown).

So, then, how do we get that? Well, the answer is ANSI Escape Sequences! These are encoded instructions included in a string to direct the console about how to change or manipulate the output. I use them in my prompt.

First, let’s just get our countdown – er, I mean countup… working. This is pretty straight forward.

This will write everything on its own line, like this.

Now, for the fanciness, what we really want is for the same line to get overwritten.

You can write an ESC inside of a string just like you would any other character. It’s represented by char 27. So we’ll set that equal to a variable $E.

Now we can embed it in strings, and we just need the rest of the sequence. If you scroll enough on that Wikipedia page linked above, you’ll get to the CSI sequences section, which basically all start with the escape character and then an open square bracket (this character: [). At the bottom of the table, you’ll notice s and u sequences for saving and restoring the cursor position.

So all we need to do is save the cursor position when we start, and then restore it each time we want to overwrite the line.

On the first line, all I’m doing is saving the cursor position. I wrap the E in $E in curly braces so it doesn’t think the square brace or the s is part of the name of the variable. You don’t have to do this for this escape sequence since the square brace isn’t a valid character in a variable name, but for some other ANSI stuff, you might want to get into this habit.

Then on the next line, I’ve just got a foreach-object loop (alias is %) that writes the same line over and over and sleeps for one second. The line it writes restores the cursor position to the one that was saved on the line above and then just writes “There are x s remaining”. We’re overwriting the same line over and over.

This works in our scenario because the line we’re writing text of the same length or longer. If you want to see this activity look a little odd, you can try something like this.

We’re saving the cursor position, writing “Hello”, waiting a second, then restoring the cursor position and writing “Hi”. We’ll see “Hello” for a second then the resulting line that comes afterwards looks like this.

This happens because we restored the cursor position and just started writing more characters. So, be careful of this if you’re using this trick in your own scripts. You can use the .PadRight() and .PadLeft() methods that are built into strings to try to fix this, or something more dynamic like detect the length of the strings you’re writing.

Notice on the last line, I’m using the .PadRight() method to add 20 characters of whitespace which will overwrite all of the rest of the text that wasn’t being overwritten before.

One thought on “PowerShell Tip: Another Take On Progress Reporting

  1. I was writing a function that performed a VM build action in Azure where there is no way of knowing how long the action has to go, I wanted to show the user that the function was still working and making progress.
    To accomplish this, I wrote some basic code which wrote a new line every 20 seconds, with each new line making up a complete image (credit MS), the image just repeats itself until the action is complete.

    ## Progress Art
    $AzureAscci = [pscustomObject] @{
    “1” = ” _ _____ _ ___ ___”
    “2” = ” /_\ |_ / | | | _ \ __|”
    “3” = ” _ ___/ _ \__/ /| |_| | / _|___ _ _”
    “4” = ” (___ /_/ \_\/___|\___/|_|_\___| _____)”
    “5” = ” (_______ _ _) _ ______ _)_ _”
    “6” = ” (______________ _ ) (___ _ _)”
    } # END-PSCUSTOMOBJECT

    ## Set Progress Counter
    $i = 1

    ## Write out-put while the job is running
    while ((Get-Job $job.id).State -eq “Running”) {
    $Status = (get-azurermvm | where-object name -eq $VMNameRecovered).ProvisioningState
    $time = get-date -format T
    $time = $time.Replace(” PM”, “”)
    $time = $time.Replace(” AM”, “”)
    Write-Host -ForegroundColor Yellow “[$($time)] [$($Status)] $($AzureAscci.$i)”
    if ($i -eq 6) {$i = 1} else {$i++}
    Start-Sleep -Seconds 20
    } ## END WAIT FOR JOB TO COMPLETE

Leave a Reply

Your email address will not be published. Required fields are marked *