配置解决Powershell输出中文乱码

把下面的配置添加到Powershell的配置文件中,每次打开Powershell都会自动生效了,当然先建议临时修改看看有没有用。

打开配置文件:

1
nvim $PROFILE

添加配置:

1
2
3
4
5
# set powershell fileencoding UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
# set Get-Content(cat) fileencoding UTF8
$PSDefaultParameterValues['Get-Content:Encoding'] = 'UTF8'

我使用neovim编辑,如果没有这个文件可以新建一个:

powershell管理员模式下:

1
nvim $PROFILE

或者去C:\Users\[用户名]\Documents\WindowsPowerShell目录下新建一个Microsoft.PowerShell_profile.ps1文件,用记事本编辑。

乱码多半是文件编码和shell输出编码不匹配的原因,我们统一选择使用utf-8编码,可以先临时配置先看看效果。

先查看文件编码是不是utf-8编码,方法非常多,比如用记事本或者其他什么编辑器打开,一般右下角就会有显示。

临时设置直接执行命令就好,设置cat(Get-Content)命令使用utf-8编码:

1
$PSDefaultParameterValues['Get-Content:Encoding'] = 'UTF8'

然后用cat命令检查一下乱码是否好了。

再就是可执行文件的中文输出,先执行下面的命令再执行可执行文件:

1
2
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

看到修改生效了再写到配置文件中,如果不生效重新启动一个Powershell窗口环境不变,寻找其他方法。

git status 显示不出中文

有时候可能会碰到这种情况:

1
2
3
4
5
6
7
8
9
@cola ➜ blog git(main) git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
(use "git push" to publish your local commits)

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: "source/_posts/tcp-ip\347\274\226\347\250\213.md"

这是因为 Git 默认会对非 ASCII 字符(比如中文)的文件名进行八进制转义,以确保在旧终端或跨平台场景下不会出现乱码。

运行以下命令,关闭路径转义:

1
git config --global core.quotePath false

core.quotePath 默认为 true,Git 会把高字节字符(非 ASCII)转义为 \xxx 形式。

将其改为false之后:

1
2
3
4
5
6
7
8
9
@cola ➜ blog git(main) git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
(use "git push" to publish your local commits)

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: source/_posts/tcp-ip编程.md