powershellwrite-host

PowerShell: -NoNewLine overlaps new-line with last-line


This is my first try writing a PowerShell script

I made this example to explain my problem:

Write-Host -NoNewLine "`rthis-is-my-first-line"
Start-Sleep -Milliseconds 1000

Write-Host -NoNewLine "`rSECONDLN"
Start-Sleep -Milliseconds 500

Write-Host

Output: SECONDLNmy-first-line but I want it to be SECONDLN only

Problem: the previous printed line is longer than the new one

Question: Is there a way to 'delete/replace' previous printed line? or how may I achieve this?


Solution

  • Therefore, in order to effectively erase the current line, you need to pad the replacement with spaces to the end of the line, which you can achieve via the .PadRight() .NET method, which by default pads with space characters, which, in effect, clear the remainder of the line:

    Write-Host -NoNewLine "`rSECONDLN".PadRight([Console]::WindowWidth)
    

    The above works in both Windows PowerShell and PowerShell 7.

    As Daniel points out, in PowerShell (Core) 7 (on all supported platforms), you can alternatively use ANSI / VT escape sequence `e[2K to clear the entire line first:

    Write-Host -NoNewLine "`r`e[2KSECONDLN"
    

    Alternatively, you can clear to the end of the line (the equivalent of the .PadRight() solution; the 0 in the escape sequence is optional):

    Write-Host -NoNewLine "`rSECONDLN`e[0K"