Powershell - 如何读取 Ansi CSV 文件

标签 powershell powershell-7.2

Notepad++ 表示 CSV 文件是 Ansi 编码的。

Powershell 7 Import-CSV commandlet 有各种编码选项,但“Ansi”不是其中之一。

如何让 Powershell 读取此 CSV 而不会损坏它?

-Encoding 的选项有:

  • ascii
  • bigendianunicode
  • bigendianutf32
  • OEM
  • 统一码
  • utf7
  • utf8
  • utf8BOM
  • utf8NoBOM
  • utf32

最佳答案

使用 ANSI 编码,即事件旧系统区域设置(非 Unicode 程序的语言)隐含的特定代码页,例如 Windows-1252 :

  • 在 Windows PowerShell 中:

    -Encoding Default
    
  • 在您使用的 PowerShell (Core) 7+ 中,Default 现在指的是 UTF-8,因此需要做更多工作:

    • 在 PowerShell v7.3- 中:

      -Encoding ([cultureinfo]::CurrentCulture.TextInfo.ANSICodePage)
      
    • 在 PowerShell v7.4+ 中:[1]

      -Encoding Ansi
      

两个 PowerShell 版本中的默认字符编码:

  • Windows PowerShell,旧版、仅限 Windows、附带 Windows 版本(其最新且最后版本为v5.1.x),默认为关键区域中的事件 ANSI 代码页 - 特别是 Get-Content/Set-Content 以及当 PowerShell 引擎读取源代码时 - 但内置 cmdlet 的默认值差异很大;举个例子:Import-Csv 默认为 UTF-8;请参阅 this answer 的底部部分以获得概述。

  • PowerShell (Core) ,现代的按需安装跨平台版本(从 v6 开始,目前为 v7.2.x),幸运的是现在始终默认为(无 BOM) UTF-8.


[1] 早期 PowerShell(核心)版本中缺少 Ansi -Encoding 值是一个奇怪的遗漏,因为 Oem 值(对于事件 OEM 代码页)始终存在 - 请参阅 GitHub issue #6562背景故事。

关于Powershell - 如何读取 Ansi CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74110642/

相关文章:

powershell - 为什么进程 block 正确返回哈希表,而不是哈希表数组?

powershell - Windows 10 iot 树莓派 3 wifi 热点

powershell - 为什么 $env:username 和 [environment]::username 会返回不同的用户?

windows - 管理员模式与非管理员模式 - 无法覆盖变量,因为变量已被优化

powershell - PSCustomObject 不喜欢 NoteProperty 值中的内联 if 语句

.net - PowerShell - 尝试在没有自签名证书问题的情况下进行 REST 调用的添加类型问题

.net - 为什么将PSObject添加到Powershell中的ArrayList需要这么长时间?有更好的方法吗?

powershell - 从命令行 PowerShell 7.2 传递哈希表参数

Azure Powershell - 根据私有(private)IP查找NIC

powershell - ShouldProcess 在 PowerShell7 中失败