例如,如果您在 powershell 会话中执行此命令
write-host 'hello' -ForegroundColor 'red' -BackgroundColor 'cyan'
调整窗口大小会导致背景颜色填充整行:
我已经在 Windows 终端、Windows 控制台和 Fluent 终端中对此进行了测试,它们都表现出这种行为。 (我猜测可能有一个虚拟终端序列/ANSI 代码来解决这个问题,但我不知道这可能是什么)。
那么,我们怎样才能防止这种情况发生呢?
λ $PSVersionTable
Name Value
---- -----
PSVersion 7.1.1
PSEdition Core
GitCommitId 7.1.1
OS Microsoft Windows 10.0.19041
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
编辑:作为测试,我尝试了以下操作:
write-host 'hello' -ForegroundColor 'red' -BackgroundColor 'cyan' -NoNewline; write-host 'world' -BackgroundColor black
当然会显示“HelloWorld”,“世界显示没有背景颜色,或更准确地说与默认颜色(黑色)相同。”
如果我们再向前迈出一步,在背景颜色设置为黑色后打印一个额外的空格,那么这不会达到预期的响应,IE 我们会在调整大小后看到背景颜色青色填充整行.因此,我们需要某种不可见的字符来阻止背景颜色溢出,或者需要一种我目前不知道的完全不同的方法。
conhost
中确认的 bug
。因此,所有依赖于
conhost
的东西都会有这个 bug。这是 Windows 控制台中的错误,而不是 Powershell 中的错误。它在 powershell 之外有问题(尝试
this,例如)。
控制台使用最后一个字符的颜色填充行,该颜色不是空格(0x20),也不是制表符(0x09),也不是换行符。您可以尝试以下解决方案之一:
1 - 在行尾使用
Non-Breaking space 字符空间。这是唯一一个空格单字节字符,它是空格,不会被控制台忽略,也不是换行符。
write-host 'hello' -f 'red' -b 'cyan' -n; write-host ([char]0xA0)
2 - 使用颜色与控制台颜色匹配的任何字符。这更糟糕,因为它被复制到剪贴板、输出等。
$hostBgColor = $Host.UI.RawUI.BackgroundColor
write-host 'hello' -f 'red' -b 'cyan' -n; write-host 'X' -f $hostBgColor -b $hostBgColor
3 - 使用其他 unicode 多字节