从PowerShell脚本向json文件添加版权字符

x759pob2  于 2022-11-29  发布在  Shell
关注(0)|答案(2)|浏览(97)

我有一个用当前年份更新配置文件的脚本,但由于某种原因,版权符号没有正确插入。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版本。

aemubtdh

aemubtdh1#

假设您运行的是***Windows PowerShell***,并且希望读取输入并创建 UTF-8 编码的输出:

  • 如果可以使用BOM*创建UTF-8文件 *(Windows PowerShell中的Set-Content -Encoding utf8总是创建此文件):
# Note the use of -Encoding utf8 in both statements.
# (In PowerShell (Core) 7+, neither would be needed,
# and Set-Content would create a BOM-*less* UTF-8 file;
# you'd need -Encoding utf8BOM to create one *with* a BOM).

$a = Get-Content -Encoding utf8 $path| ConvertFrom-Json
# ...
$a | ConvertTo-Json | Set-Content -Encoding utf8 $path
  • 创建UTF-8文件 * 而不使用BOM*需要在Windows PowerShell中进行更多工作(而此编码现在是PowerShell (Core) 7+中的 * 一致默认值 *),利用New-Item(当给定-Value参数时)(总是)使用该编码创建文件这一奇怪的事实:
# (In PowerShell (Core) 7+, -Encoding utf8 wouldn't be needed,
# and Set-Content would create a BOM-*less* UTF-8 file by default.)

$a = Get-Content -Encoding utf8 $path| ConvertFrom-Json
# ...
New-Item -Force -Path $path -Value (($a | ConvertTo-Json) + "`r`n")

注意事项:

  • 月日阅读:PowerShell可自动识别Unicode BOM,但在 * 不存在 * BOM的情况下 * 采用的编码方式取决于PowerShell版本,无论是在阅读源代码时还是在通过cmdlet(如通过Get-Content)读取文件时:
    *Windows PowerShell采用系统的传统ANSI代码页(也称为非Unicode程序的语言)。
    *PowerShell(核心)采用UTF-8
  • 于× ×年×月×日行文× ×:读取文件后,PowerShell * 不会 * 保留有关输入文件原始字符编码的信息-文件内容存储在.NET字符串中(其由存储器中的UTF-16 LE代码单元组成),即使当数据简单地通过管线传递时。因此,如果未指定-Encoding参数,则使用文件写入cmdlet自己的 * 默认 * 编码,而不管数据来自何处;具体而言:
    *Windows PowerShell的Set-Content默认为系统传统ANSI编码;不幸的是,其他cmdlet具有 * 不同的 * 默认值;值得注意的是,
    Out-File及其虚拟别名>默认为UTF-16 LE(“Unicode”)
    -有关详细信息,请参阅this answer的底部部分。
    *PowerShell(核心)现在幸运地默认为所有 * cmdlet的无BOM UTF-8。
sbtkgmzw

sbtkgmzw2#

无法重现问题:
第一个
若要在PowerShell中使用任何外部程序显示结果,请参阅:Displaying Unicode in Powershell

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding =  New-Object System.Text.UTF8Encoding

相关问题