powershellconsole

How to change cursor position in powershell console


I currently assign the current CursorPosition to a variable in Powershell so that I can overwrite the same space when performing a count down for example in a script, as below:

$errorPos = $host.UI.RawUI.CursorPosition
for ($i=5; $i -ge 0; $i--) {
    $host.UI.RawUI.CursorPosition = $errorPos
    Write-Host -NoNewline -BackgroundColor Yellow -ForegroundColor Black "$i"
    Start-Sleep -Seconds 1
}

What I'd like to do, it take the current position of the cursor and move it forward two spaces, then assign it to another variable. I could just use:

write-host "  "

but I don't want to overwrite the text currently occupying that space.

I think it can be accomplished using X and Y coordinate but am not having much success.


Solution

  • If you just want to move the 'X' forward by 2 you can just do this after creating your errorPos variable:

    $errorPos.X += 2
    

    You can modify the variable directly by using $errorPos.X and .Y.