我有一个用当前年份更新配置文件的脚本,但由于某种原因,版权符号没有正确插入。PowerShell脚本是带BOM的UTF-8,JSON文件是UTF-8。
工作流程是从JSON文件读取,更新版权日期,然后再次保存到JSON文件。
JSON文件info.json
:
{
"CopyrightInfo": "Copyright © CompanyName 1992"
}
PowerShell脚本的可复制摘录:
$path = "./info.json"
$a = Get-Content $path| ConvertFrom-Json
$a.'CopyrightInfo' = "Copyright $([char]::ConvertFromUtf32(0x000000A9)) CompanyName $((Get-Date).Year)"
$a | ConvertTo-Json | set-content $path
我已经尝试了很多方法,上面是最新的尝试。当在PowerShell中打印或在记事本中打开时,它看起来很好,但任何其他编辑器(Visual Studio代码,SourceTree,Azure DevOps文件查看器等),它们总是导致以下结果:
"CopyrightInfo": "Copyright � CompanyName 2022"
如果有人能解释我做错了什么,那将是伟大的,甚至更大,如果他们也可以添加一种方法,使它正常工作。
我使用的是PowerShell版本5.1.19041.1682
编辑:使用可重现的代码摘录更新了问题,并使用了PowerShell版本。
2条答案
按热度按时间aemubtdh1#
假设您运行的是***Windows PowerShell***,并且希望读取输入并创建 UTF-8 编码的输出:
Set-Content -Encoding utf8
总是创建此文件):New-Item
(当给定-Value
参数时)(总是)使用该编码创建文件这一奇怪的事实:注意事项:
Get-Content
)读取文件时:*Windows PowerShell采用系统的传统ANSI代码页(也称为非Unicode程序的语言)。
*PowerShell(核心)采用UTF-8。
-Encoding
参数,则使用文件写入cmdlet自己的 * 默认 * 编码,而不管数据来自何处;具体而言:*Windows PowerShell的
Set-Content
默认为系统传统ANSI编码;不幸的是,其他cmdlet具有 * 不同的 * 默认值;值得注意的是,Out-File
及其虚拟别名>
默认为UTF-16 LE(“Unicode”)-有关详细信息,请参阅this answer的底部部分。*PowerShell(核心)现在幸运地默认为所有 * cmdlet的无BOM UTF-8。
sbtkgmzw2#
无法重现问题:
第一个
若要在PowerShell中使用任何外部程序显示结果,请参阅:Displaying Unicode in Powershell