PowerShell write-host background color continuing past the code
Asked Answered
J

1

5

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.

Jacintojack answered 16/1, 2023 at 12:35 Comment(3)
I don't know the answer but as a workaround you could use ANSI escape coloring, which is pretty easy to use through the global $PSStyle variable: Write-Host "$($PSStyle.Foreground.Magenta)$($PSStyle.Background.White)text text text$($PSStyle.Reset)" -- this explicitly resets the style which should avoid any "bleeding" into the command-line.Theretofore
This doesnt happen in other editors, so I suspect it's more a vscode issue than a Powershell one.Bund
I mean I don't know, did you even see the Windows Terminal screenshot in the post? @Theretofore thank you very much, yes that indeed stopped the bleeding, now no matter how fast I spam it, no bleeding occurs anywhere. want to add it as answer?Jacintojack
T
8

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.

Theretofore answered 16/1, 2023 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.