Files
MemRelay/global/Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件.md
memrelay 55b8317579 create: Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件
MemRelay-Operation: memory-save:global-exp-ps51-encoding-20260930-a1
MemRelay-Resource: b1d6b466-629c-45dc-b041-652e2c2925ae
2026-09-30 14:04:09 +08:00

1.5 KiB

title, type, permalink, stable_id, scope, memory_type, project_id, usage_profile_id, status, revision, request_id, created_at, updated_at, tags
title type permalink stable_id scope memory_type project_id usage_profile_id status revision request_id created_at updated_at tags
Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件 experience main/global/windows-power-shell-5.1-脚本与中文脚本保持纯-ascii-中文放-utf-8-文件 b1d6b466-629c-45dc-b041-652e2c2925ae global experience null 0c9feb46-d06e-43cd-9ef0-c5813c84a998 active 1 global-exp-ps51-encoding-20260930-a1 2026-09-30T06:04:05.431813+00:00 2026-09-30T06:04:05.431813+00:00
powershell
windows
encoding
utf-8
  • Windows PowerShell 5.1 按系统代码页(中文 Windows 为 GBK)解析无 BOM 的 .ps1。脚本里的中文字面量会乱码,甚至引发解析错误(字符串被截断、括号不配对)。命令行里直接写的中文正则同样会被破坏。
  • 做法:.ps1 只写 ASCII;中文放 UTF-8 的模板或 JSON 文件,用 [IO.File]::ReadAllText(path, [Text.Encoding]::UTF8) 读取;写文件用 [IO.File]::WriteAllText(path, text, (New-Object Text.UTF8Encoding($false)))。另一种办法是给 .ps1 加 UTF-8 BOM。
  • 5.1 下 Add-Content / Out-File 的默认编码不是 UTF-8,追加到 Go 等 UTF-8 源码会导致 invalid UTF-8 encoding。
  • 管道里的 Select-Object -First N 会提前终止上游(包括子 powershell 进程)。不要用它截断仍在执行写操作的脚本的输出,应让脚本跑完或把输出写到文件。
  • for 循环语句不能直接接管道;需要管道时用 ForEach-Object 或先收集到变量。