8 Nov 2018

PowerShell - Writing to the same line with Write-Host

This is a PowerShell tip that I’m posting for future use. If you want to write information to the same line using the Write-Host cmdlet, you use the –NoNewLine switch:

Write-Host "Countdown - $index seconds remaining" –NoNewline

If you want to overwrite the previous content written, you can use the carriage return character (courtesy of this StackOverflow answer by Dullson):

Write-Host "`rCountdown - $index seconds remaining" –NoNewline

Note, you may need to use spaces to blank out previous content if the previous string is longer than the new content string:

Write-Host "`rCompleted $seconds second countdown.     "

Note, the line above doesn’t use the –NoNewLine switch, so new further content can be written to that line in the console. I’ve used this PowerShell snippet for a simple sleep timer with a visual countdown, when I didn’t want to use the default progress indicator (the Write-Progress cmdlet).

No comments:

Post a Comment