Peter Kapteyn
Peter Kapteyn

Reputation: 405

How to print over text powershell

enter image description here

I'm trying to write a powershell script that implements a typing speed test. I'm looking to make it look something like this picture. So you print some text to the console, then print over it in a different font color. I have all the parts of the script worked out, except for printing over the text I already printed.

For a single line, its easy, just do something like write-host "mytext 'r -NoNewLine, and then the cursor is set back to the beginning of the line, but this method doesn't work if I want to output a multiline string, then print back over it.

Any ideas on how I could accomplish something like this in powershell?

Upvotes: 4

Views: 1448

Answers (1)

mklement0
mklement0

Reputation: 437288

You can use $host.UI.RawUI.CursorPosition to query and set the cursor position, as the following example shows (via the automatic $Host variable; for the specific property see here).

Note that an X value of 0 refers to the first usable column on the line (where you can type), i.e. after the prompt string.

A simple demonstration:

# Write a line at the top of the screen (first line)
Clear-Host
Write-Host ('x' * 20) -ForegroundColor Gray

# Place the cursor back at the start of the first line
$host.UI.RawUI.CursorPosition = @{ x = 0; y = 0 }

# Partially overwrite the original line.
Write-Host ('y' * 10) -ForegroundColor Yellow

Upvotes: 4

Related Questions