# PowerShell UTF-8 编码配置完全指南

## 问题背景

在 Windows 系统中使用 PowerShell 时,经常遇到中文乱码问题,主要原因是 PowerShell 默认使用 GB2312 编码,而现代开发环境(如 Python、Node.js 等)普遍使用 UTF-8 编码。

### 常见乱码场景

- Python 脚本输出中文时显示乱码

- 批处理文件(.bat)执行时中文显示异常

- 读取 UTF-8 编码的文本文件内容错乱

- 管道重定向输出时中文字符丢失

- Git 提交信息、日志输出等显示不正常

## 问题诊断

### 检查当前编码设置

```powershell

# 查看 PowerShell 编码信息

Write-Host "输出编码: $([Console]::OutputEncoding.EncodingName)"

Write-Host "输入编码: $([Console]::InputEncoding.EncodingName)"

Write-Host "默认编码: $([System.Text.Encoding]::Default.EncodingName)"

```

**问题表现:**

```

输出编码: Chinese Simplified (GB2312)  ← 问题所在

输入编码: Chinese Simplified (GB2312)  ← 问题所在

默认编码: Unicode (UTF-8)

```

### 创建测试脚本验证问题

**Python 测试脚本 (test_encoding.py):**

```python

print("你好,世界! Hello World!")

print("中文字符: 股票、交易、策略、回测")

print("✅ 成功 ❌ 失败 📈 上涨 📉 下跌")

print(f"标准输出编码: {sys.stdout.encoding}")

```

**PowerShell 测试脚本 (test_encoding.ps1):**

```powershell

Write-Host "你好,世界! Hello World!"

Write-Host "输出编码: $([Console]::OutputEncoding.EncodingName)"

```

## 解决方案

### 方案一:PowerShell Profile 永久配置(推荐)

PowerShell Profile 是类似于 Linux 中 `.bashrc` 的配置文件,在每次 PowerShell 启动时自动执行。

#### 步骤 1: 查看 Profile 路径

```powershell

# 显示当前用户的 Profile 文件路径

$PROFILE

```

通常路径为:

```

C:\Users\<用户名>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

```

#### 步骤 2: 创建 Profile 文件(如果不存在)

```powershell

# 检查 Profile 是否存在

Test-Path $PROFILE

# 如果不存在,创建它(包括必要的目录)

if (!(Test-Path $PROFILE)) {

    New-Item -Path $PROFILE -ItemType File -Force

}

```

#### 步骤 3: 编辑 Profile 文件

```powershell

# 使用记事本打开

notepad $PROFILE

# 或使用 VS Code 打开

code $PROFILE

```

#### 步骤 4: 添加 UTF-8 编码配置

在 Profile 文件中添加以下内容:

```powershell

# ========================================

# PowerShell UTF-8 编码配置

# ========================================

# 设置控制台输出编码为 UTF-8

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

[Console]::InputEncoding = [System.Text.Encoding]::UTF8

# 设置 PowerShell 默认编码为 UTF-8

$PSDefaultParameterValues['*:Encoding'] = 'utf8'

# 设置环境变量,确保子进程也使用 UTF-8

$env:PYTHONIOENCODING = "utf-8"

$env:LANG = "zh_CN.UTF-8"

# 可选:显示启动提示

# Write-Host "✅ UTF-8 编码已启用" -ForegroundColor Green

```

#### 步骤 5: 重新加载 Profile

```powershell

# 立即应用配置(无需重启 PowerShell)

. $PROFILE

```

#### 步骤 6: 验证配置

```powershell

# 检查编码设置

[Console]::OutputEncoding

[Console]::InputEncoding

# 运行测试脚本

python .\test_encoding.py

.\test_encoding.ps1

```

**预期结果:**

```

输出编码: Unicode (UTF-8)  ← 修复成功

输入编码: Unicode (UTF-8)  ← 修复成功

默认编码: Unicode (UTF-8)

```

### 方案二:一键配置脚本

如果想快速配置,可以直接运行以下命令:

```powershell

# 创建 Profile(如果不存在)

if (!(Test-Path $PROFILE)) { 

    New-Item -Path $PROFILE -ItemType File -Force 

}

# 添加 UTF-8 配置到 Profile

@"

# PowerShell UTF-8 编码配置

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

[Console]::InputEncoding = [System.Text.Encoding]::UTF8

`$PSDefaultParameterValues['*:Encoding'] = 'utf8'

`$env:PYTHONIOENCODING = 'utf-8'

`$env:LANG = 'zh_CN.UTF-8'

"@ | Add-Content $PROFILE

# 立即生效

. $PROFILE

# 验证

Write-Host "✅ UTF-8 编码配置完成!" -ForegroundColor Green

[Console]::OutputEncoding

```

### 方案三:临时设置(单次会话有效)

如果只想在当前 PowerShell 会话中使用 UTF-8:

```powershell

# 临时设置编码为 UTF-8

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

[Console]::InputEncoding = [System.Text.Encoding]::UTF8

$PSDefaultParameterValues['*:Encoding'] = 'utf8'

```

**注意:** 关闭 PowerShell 后此设置失效。

## PowerShell Profile 详解

### Profile 类型

PowerShell 支持多种级别的 Profile:

```powershell

# 查看所有 Profile 路径

$PROFILE | Get-Member -Type NoteProperty

```

| Profile 类型 | 作用范围 | 路径变量 |

|-------------|---------|---------|

| 当前用户,当前主机 | 最常用 | `$PROFILE.CurrentUserCurrentHost` |

| 当前用户,所有主机 | 所有 PowerShell 环境 | `$PROFILE.CurrentUserAllHosts` |

| 所有用户,当前主机 | 系统级配置 | `$PROFILE.AllUsersCurrentHost` |

| 所有用户,所有主机 | 全局配置 | `$PROFILE.AllUsersAllHosts` |

**推荐使用:** `CurrentUserCurrentHost`(默认的 `$PROFILE`)

### 执行策略问题

如果遇到"无法加载文件,因为在此系统上禁止运行脚本"错误:

```powershell

# 查看当前执行策略

Get-ExecutionPolicy

# 设置执行策略(以管理员身份运行 PowerShell)

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

```

**执行策略说明:**

- `Restricted`: 禁止运行任何脚本(默认)

- `RemoteSigned`: 本地脚本可运行,远程脚本需签名

- `Unrestricted`: 允许运行所有脚本(不推荐)

### Profile 常用配置示例

```powershell

# ========================================

# PowerShell Profile 完整配置示例

# ========================================

# 1. UTF-8 编码配置

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

[Console]::InputEncoding = [System.Text.Encoding]::UTF8

$PSDefaultParameterValues['*:Encoding'] = 'utf8'

# 2. 环境变量配置

$env:PYTHONIOENCODING = "utf-8"

$env:LANG = "zh_CN.UTF-8"

# 3. 常用别名

Set-Alias ll Get-ChildItem

Set-Alias g git

Set-Alias py python

# 4. 自定义函数

function prompt {

    $location = Get-Location

    "PS $location> "

}

function mkcd {

    param($dir)

    New-Item -ItemType Directory -Path $dir -Force | Out-Null

    Set-Location $dir

}

# 5. 启动脚本

# & "E:\development\scripts\startup.ps1"

# 6. 启动信息

Write-Host "✅ PowerShell 已就绪 (UTF-8)" -ForegroundColor Green

```

## 验证与测试

### 完整测试脚本

创建 `test_encoding.py`:

```python

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import sys

print("=" * 50)

print("编码测试")

print("=" * 50)

print("中文字符: 你好世界,股票交易")

print("特殊符号: ¥ € $ £ ° → ← ↑ ↓")

print("Emoji: ✅ ❌ 📈 📉 🚀 💰")

print(f"Python 编码: {sys.stdout.encoding}")

print(f"文件系统编码: {sys.getfilesystemencoding()}")

print("=" * 50)

```

创建 `test_encoding.ps1`:

```powershell

Write-Host "=" * 50

Write-Host "PowerShell 编码测试"

Write-Host "=" * 50

Write-Host "中文字符: 你好世界,股票交易"

Write-Host "特殊符号: ¥ € $ £ ° → ← ↑ ↓"

Write-Host "Emoji: ✅ ❌ 📈 📉 🚀 💰" -ForegroundColor Cyan

Write-Host "输出编码: $([Console]::OutputEncoding.EncodingName)"

Write-Host "输入编码: $([Console]::InputEncoding.EncodingName)"

Write-Host "=" * 50

```

### 运行测试

```powershell

# 测试 Python 脚本

python .\test_encoding.py

# 测试 PowerShell 脚本

.\test_encoding.ps1

# 测试文件读写

"你好世界 UTF-8 测试" | Out-File test.txt -Encoding UTF8

Get-Content test.txt

```

### 预期正常输出

所有中文、emoji、特殊符号应正常显示,编码信息应为:

```

输出编码: Unicode (UTF-8)

输入编码: Unicode (UTF-8)

Python 编码: utf-8

```

## 常见问题排查

### 1. Profile 不生效

**问题:** 修改了 Profile 但设置没有生效

**解决:**

```powershell

# 检查 Profile 文件是否存在

Test-Path $PROFILE

# 手动加载 Profile

. $PROFILE

# 检查是否有语法错误

Get-Content $PROFILE

```

### 2. 批处理文件乱码

**问题:** `.bat` 文件执行时仍然乱码

**原因:** 批处理文件本身可能不是 UTF-8 编码

**解决:**

```powershell

# 将批处理文件转换为 UTF-8

Get-Content .\file.bat -Encoding Default | Set-Content .\file_utf8.bat -Encoding UTF8

```

### 3. Git 输出乱码

**问题:** Git 命令输出中文乱码

**解决:**

```powershell

# 在 Profile 中添加

$env:LANG = "zh_CN.UTF-8"

# 或配置 Git

git config --global core.quotepath false

git config --global gui.encoding utf-8

git config --global i18n.commit.encoding utf-8

git config --global i18n.logoutputencoding utf-8

```

### 4. 文件重定向乱码

**问题:** 使用 `>` 或 `>>` 重定向时乱码

**解决:**

```powershell

# 使用 Out-File 并指定编码

command | Out-File output.txt -Encoding UTF8

# 或使用 Set-Content

command | Set-Content output.txt -Encoding UTF8

```

### 5. VSCode 集成终端乱码

**问题:** VSCode 终端中文显示异常

**解决:** 在 VSCode 的 `settings.json` 中添加:

```json

{

    "terminal.integrated.defaultProfile.windows": "PowerShell",

    "terminal.integrated.profiles.windows": {

        "PowerShell": {

            "source": "PowerShell",

            "args": ["-NoExit", "-Command", "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8"]

        }

    }

}

```

## 相关资源

### PowerShell Profile 位置

```powershell

# 当前用户配置

$PROFILE

# 通常位于: C:\Users\<用户名>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

# 所有用户配置

$PROFILE.AllUsersCurrentHost

# 通常位于: C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1

```

### 快速编辑命令

```powershell

# 编辑 Profile

notepad $PROFILE

code $PROFILE

# 查看 Profile 内容

cat $PROFILE

Get-Content $PROFILE

# 重新加载 Profile

. $PROFILE

& $PROFILE

```

## 总结

### 核心配置(必须)

```powershell

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

[Console]::InputEncoding = [System.Text.Encoding]::UTF8

$PSDefaultParameterValues['*:Encoding'] = 'utf8'

```

### 配置位置

将上述配置添加到 `$PROFILE` 文件中,实现每次启动自动生效。

### 验证方法

```powershell

# 检查编码

[Console]::OutputEncoding

# 测试输出

Write-Host "你好世界 ✅ 📈"

python -c "print('你好世界 ✅ 📈')"

```

### 注意事项

1. ✅ 推荐使用 PowerShell 7+(跨平台版本)

2. ✅ 文件编辑器保存为 UTF-8 编码(无 BOM)

3. ✅ 配置后重新加载 Profile 或重启 PowerShell

4. ❌ 避免使用旧版 Windows PowerShell(5.1)的编码设置

5. ❌ 不要混用不同编码的文件和脚本

---

**配置完成后,PowerShell 将完美支持中文、emoji 和各种 UTF-8 编码的内容!** 🎉