轶哥

📚 Having fun with AI Agent. Always learning.

Powershell7 中文乱码问题解决
  •   更新:2022-04-06 21:35:50
  •   首发:2022-04-06 17:14:02
  •   教程
  •   4682

修改$Profile文件(notepad.exe $Profile),添加

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding

说明:上述操作修改了输出编码为UTF-8,兼容了大部分的程序输出的中文。

需要注意的是,PowerShell7仅修改chcp 65001无法实现对程序输出中文的支持。另外,修改控制面板-区域-管理-更改系统区域设置里面的设置,启用Beta版:使用Unicode UTF-8提供全球语言支持,也可以达到同样的效果,但是很多中文应用程序,包括操作系统自带的应用程序,将会出现中文显示异常。不推荐此方案!

区域设置.png

以上方法在win10、win11系统安装的Powershell 7.2.2版本测试通过。

如果上述操作后仍然无法正常显示中文,应该是没有正确配置中文字体。推荐安装windows terminal,设置等宽且支持中文的字体。推荐支持Retina的等宽字体FiraCode Nerd Font Mono Retina

terminal.png

如果在VSCode中无法正常显示,参考以下配置:

{
  "terminal.external.windowsExec": "C:\\Program Files\\PowerShell\\7\\pwsh.exe --nologo",
  "editor.fontFamily": "'FiraCode Nerd Font Mono Retina', 'Microsoft YaHei Mono', Consolas, 'Courier New', monospace",
  "terminal.integrated.minimumContrastRatio": 1,
  "terminal.integrated.defaultProfile.windows": "PowerShell",
  "terminal.integrated.profiles.windows": {
    "PowerShell": {
      "path": "C:\\Program Files\\PowerShell\\7\\pwsh.exe",
      "args": [
        "--nologo"
      ],
      "source": "PowerShell",
      "icon": "terminal-powershell"
    }
  }
}

vscode.png

其中minimumContrastRatio是终端无法正常显示文字背景色的配置方法。

打赏
交流区(1)
轶哥

公开一下我目前学习大佬操作后整理的C:\Users\admin\Documents\PowerShell\Microsoft.PowerShell_profile.ps1配置文件:

Import-Module posh-git # 引入 posh-git
Import-Module oh-my-posh # 引入 oh-my-posh

Set-PoshPrompt bubbles # 设置主题为 bubbles

Set-PSReadLineOption -PredictionSource History # 设置预测文本来源为历史记录
 
Set-PSReadlineKeyHandler -Key Tab -Function Complete # 设置 Tab 键补全
Set-PSReadLineKeyHandler -Key "Ctrl+d" -Function MenuComplete # 设置 Ctrl+d 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo # 设置 Ctrl+z 为撤销

Set-PSReadLineKeyHandler -Key UpArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchBackward()
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
} # 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key DownArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchForward()
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
} # 设置向下键为前向搜索历史纪录

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
2022年4月6日 09:17回复
尚未登陆
发布
  上一篇 (Win11 多用户同时登录远程桌面配置方法)
下一篇 (OpenWRT使用4G/5G无线网卡模块上网)  

评论回复提醒