如题,万恶的PowerShell重定向时默认的文本编码是UTF-16 LE,简直反人类!虽然在PowerShell 6+中默认改为了UTF-8 NO-BOM,但最新版Windows中内置的仍旧是5.1版本。

好在5.1下我们可以修改默认值,将重定向时从UTF-16改为UTF-8 BOM(遗憾的是该版本不能默认NO-BOM)。根据 https://stackoverflow/questions/40098771/changing-powershells-default-output-encoding-to-utf-8 和 https://blog.csdn/qq_43780850/article/details/129122210 :

管理员身份打开powershell,*注意,以管理员身份,不然不能生效,*依次执行如下命令:

#允许运行自定义脚本
set-executionpolicy remotesigned

#创建默认profile,如果存在则不创建
if (!(Test-Path -Path $PROFILE)) {
  New-Item -ItemType File -Path $PROFILE -Force
}

#查看创建的profile文件位置
$PROFILE

根据输出的位置,找到profile文件,例如C:\Users\Yuanfei\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

使用文本编辑器打开这个文件,加入一行:

$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

然后新打开的PowerShell重定向时编码就会变为UTF-8 BOM了。

对于PowerShell 5.0的版本,进行这样设置后,使用>>>重定向是不行的,必须通过Out-File命令进行重定向才会生效。

echo "666" | Out-File 233.txt
echo "666" | Out-File -Append 233.txt

查看PowerShell版本:

PS D:\> $host


Name             : ConsoleHost
Version          : 5.1.22621.2506
InstanceId       : bdaa6bff-195e-45f7-8505-add09a5a5652
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : zh-CN
CurrentUICulture : zh-CN
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace