我有一個用當前年份更新組態檔的腳本,但由于某種原因,著作權符號沒有正確插入。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 Code、SourceTree、Azure DevOps 檔案查看器等)總是會導致以下結果:
"CopyrightInfo": "Copyright ? CompanyName 2022"
如果有人能解釋我做錯了什么,如果他們還可以添加一種使其正常作業的方法,那就太好了。
我正在使用 PowerShell 版本 5.1.19041.1682
編輯:更新了可重現代碼摘錄的問題并使用了 PowerShell 版本。
uj5u.com熱心網友回復:
假設您正在運行Windows PowerShell,并且您希望讀取輸入并將輸出創建為UTF-8編碼:
如果可以使用 BOM創建UTF-8 檔案(
Set-Content -Encoding utf8在 Windows PowerShell 中總是創建):# 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創建沒有 BOM的UTF-8 檔案需要在 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-16LE 代碼單元組成)中,即使資料只是通過管道傳遞。因此,如果未指定引數,則使用檔案寫入 cmdlet 自己的默認編碼
-Encoding,而不管資料來自何處;具體來說:Windows PowerShell
Set-Content默認為系統舊版ANSI編碼;不幸的是,其他 cmdlet 有不同的默認值;值得注意的是,Out-File它的虛擬別名,>默認為UTF-16LE(“Unicode”) - 有關詳細資訊,請參閱此答案的底部部分。幸運的是, PowerShell(核心)現在在所有cmdlet中默認為無 BOM 的 UTF-8。
uj5u.com熱心網友回復:
無法重現問題:
$Data = @{ CopyrightInfo = "Copyright $([char]::ConvertFromUtf32(0x000000A9)) CompanyName $((Get-Date).Year)" }
$Json = ConvertTo-Json $Data
$Json |Set-Content .\Test.json
$Json = Get-Content -Raw .\Test.json
$Data = ConvertFrom-Json $Json
$Data
CopyrightInfo
-------------
Copyright ? CompanyName 2022
要使用任何外部程式在 PowerShell 中顯示結果,請參閱:在 Powershell 中顯示 Unicode
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532940.html
標籤:电源外壳编码符号
