簡體   English   中英

Powershell 防止UTF8轉換

[英]Powershell prevent UTF8 conversion

當我嘗試使用 Powershell 操作 an.ini 文件時,它總是將編碼切換為 UTF-8。

我的代碼:

Get-Content -Path "./update.ini" -Encoding ascii | Out-File -FilePath "ascii_update.ini" -Encoding ascii

該文件需要保持 ASCII,那么如何禁用此行為或如何將其切換回 ASCII?

德語字符將無法正確顯示

鑒於您不想要 UTF-8 編碼但您想要德語變音符號,您正在尋找的是ANSI編碼,而不是ASCII

  • Windows PowerShell中,ANSI 編碼是Get-ContentSet-Content使用的默認編碼(但不是Out-File ,默認為“Unicode”(UTF-16LE)),所以您只需要以下內容:
# Windows PowerShell: ANSI encoding is the default for Get-Content / Set-Content
Get-Content ./update.ini | Set-Content ascii_update.ini
  • PowerShell (Core) 7+ , (BOM-less) UTF-8 現在是所有cmdlet 的默認值,因此您必須使用-Encoding顯式請求 ANSI 編碼

    • Unfortunately, whereas Default refers to the system's active ANSI encoding in Windows PowerShell , in PowerShell (Core) it now refers to UTF-8, and there is no predefined ANSI enumeration value to complement the OEM value - this baffling omission is discussed in GitHub issue #6562 .

    • 因此,您必須明確確定活動的 ANSI 代碼頁,如下所示。

$ansiEnc = [cultureinfo]::CurrentCulture.TextInfo.ANSICodePage
Get-Content -Encoding $ansiEnc ./update.ini |
  Set-Content -Encoding $ansiEnc ascii_update.ini

記事本在右下方顯示為 UTF-8。

ASCII 編碼是 UTF-8 編碼的子集,這就是為什么大多數編輯器將純 ASCII 文件顯示為 UTF-8 的原因,因為根據定義它們也是有效的 UTF-8 文件。

請注意,如果您使用-Encoding ASCII保存或讀取包含非 ASCII 字符的文本,則非 ASCII 字符將“有損”轉碼為逐字? 字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM