Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
freem
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Openai/682f352f-ad4c-8008-8634-2462045a20d7
(section)
Add languages
Page
Discussion
English
Read
Edit
Edit source
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
Edit source
View history
General
What links here
Related changes
Special pages
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Assistant: 你说得对,PowerShell 在用 .(点)调用 .ps1 脚本时,不会强制使用 UTF-8 编码解析脚本内容,它会依据 系统默认编码(可能是 ANSI、GBK、ASCII)进行解析,这在中文系统上常引起乱码或语法错误(如括号不匹配)。 === 你说得对,PowerShell 在用 .(点)调用 .ps1 脚本时,不会强制使用 UTF-8 编码解析脚本内容,它会依据 系统默认编码(可能是 ANSI、GBK、ASCII)进行解析,这在中文系统上常引起乱码或语法错误(如括号不匹配)。 ==== PowerShell Core(7.x+)支持通过 [Byte Order Mark (BOM)] 识别 UTF-8 编码。但如果你用的是 Windows PowerShell 5.x,它只默认使用 ANSI/GBK 编码。解决方案有两种: ==== ===== #### ===== # 打开你的 script.ps1 # 点击右下角的编码(可能写着 UTF-8 或 GB2312) # 选择 以带 BOM 的 UTF-8 重新保存 这让 PowerShell 正确识别为 UTF-8 脚本,即使是用 . 调用。 ===== <syntaxhighlight lang="powershell">powershell.exe -ExecutionPolicy Bypass -File .\script.ps1 ===== </syntaxhighlight> 或者在 PowerShell Core 中可用 -Encoding utf8 读取并 Invoke-Expression(曲线救国): <syntaxhighlight lang="powershell">Invoke-Expression (Get-Content -Path .\script.ps1 -Raw -Encoding utf8) </syntaxhighlight> ==== 你可以封装一个加载 UTF-8 脚本的函数: ==== <syntaxhighlight lang="powershell">function Invoke-Utf8Script { param([string]$Path) Invoke-Expression (Get-Content -Path $Path -Raw -Encoding UTF8) } </syntaxhighlight> 使用方式: <syntaxhighlight lang="powershell">Invoke-Utf8Script .\script.ps1 </syntaxhighlight> 这样就能绕开默认编码限制。 ==== 如果你常常要用 . .\script.ps1 加载 UTF-8 脚本,最安全的方式是: ==== * 统一所有 .ps1 文件编码为 带 BOM 的 UTF-8 * 或者,用 Invoke-Utf8Script 函数调用它们 如果你不确定脚本的编码,我可以帮你写一个检测编码并转换为 UTF-8 的脚本,要不要我提供?
Summary:
Please note that all contributions to freem are considered to be released under the Creative Commons Attribution-ShareAlike 4.0 (see
Freem:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)