powershellcolorswrite-hostpowershell-7.3

PowerShell write-host background color continuing past the code


enter image description here

this is from VS code, also happens in PowerShell 7.3 in Windows Terminal

enter image description here

the code is this:

write-host "text text text" -ForegroundColor Magenta -BackgroundColor white

that's just for a test, but it happens a lot more often when write-host is inside a big script and the background colors just keep dragging outside the text. how can I prevent this from happening? been having this problem for a couple of months.

p.s the correct word for this seems to be bleeding, so PowerShell write-host color bleeding is happening.


Solution

  • This is a known bug related to scrolling. When the output of Write-Host involves scrolling, the background color leaks into the command-line:

    1..100 | % { write-host "text text text" -ForegroundColor Magenta -BackgroundColor white }
    

    As a workaround you could use ANSI escape sequences for coloring, which is pretty easy as of PS 7.2+ by using the automatic $PSStyle variable:

    Write-Host "$($PSStyle.Foreground.Magenta)$($PSStyle.Background.White)text text text$($PSStyle.Reset)" 
    

    The $($PSStyle.Reset) explicitly resets the style at the end of the line which should avoid any background color leaking into the command-line.