From 55b83175791a91850149e86f24e06305c0ca441e Mon Sep 17 00:00:00 2001 From: MemRelay Date: Wed, 30 Sep 2026 14:04:09 +0800 Subject: [PATCH] =?UTF-8?q?create:=20Windows=20PowerShell=205.1=20?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=E4=B8=8E=E4=B8=AD=E6=96=87=EF=BC=9A=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E4=BF=9D=E6=8C=81=E7=BA=AF=20ASCII=EF=BC=8C=E4=B8=AD?= =?UTF-8?q?=E6=96=87=E6=94=BE=20UTF-8=20=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MemRelay-Operation: memory-save:global-exp-ps51-encoding-20260930-a1 MemRelay-Resource: b1d6b466-629c-45dc-b041-652e2c2925ae --- ...文:脚本保持纯 ASCII,中文放 UTF-8 文件.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 global/Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件.md diff --git a/global/Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件.md b/global/Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件.md new file mode 100644 index 0000000..c4f7daf --- /dev/null +++ b/global/Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件.md @@ -0,0 +1,26 @@ +--- +title: Windows PowerShell 5.1 脚本与中文:脚本保持纯 ASCII,中文放 UTF-8 文件 +type: experience +permalink: main/global/windows-power-shell-5.1-脚本与中文脚本保持纯-ascii-中文放-utf-8-文件 +stable_id: b1d6b466-629c-45dc-b041-652e2c2925ae +scope: global +memory_type: experience +project_id: null +usage_profile_id: 0c9feb46-d06e-43cd-9ef0-c5813c84a998 +status: active +revision: 1 +request_id: global-exp-ps51-encoding-20260930-a1 +created_at: '2026-09-30T06:04:05.431813+00:00' +updated_at: '2026-09-30T06:04:05.431813+00:00' +tags: +- 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 或先收集到变量。 \ No newline at end of file