使用TryCatchFinally避免OhMyPosh的编码污染


使用 Try-Catch-Finally 避免 OhMyPosh 的编码污染

问题

OhMyPosh 为了能够在 Powershell 中渲染其美化过的特定字符,会将 Powershell 的代码页(Codepage)重置为 65001 (UTF-8). 导致命令行工具的交互变为英文。而且不可以用 chcp 936 来解决,因为 OhMyPosh 在每一次命令执行后都会刷新输出界面,导致编码再次被覆盖。

为了验证是每次命令后刷新,可以用 chcp 936; ping 来测试,输出为中文。

Solution

这里可以使用 Try-Finally 来在 oh-my-posh 退出时自动还原编码。

PoC

$previousOutputEncoding = [Console]::OutputEncoding
[Console]::OutputEncoding = [Text.Encoding]::UTF8
try {
    oh-my-posh init pwsh --config ~/custom.omp.json | Invoke-Expression
} finally {
    [Console]::OutputEncoding = $previousOutputEncoding
}

文章作者: sfc9982
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 sfc9982 !
  目录