powershell - 为什么 Powershell 文件串联会将 UTF8 转换为 UTF16?

标签 powershell utf-8 utf-16 data-conversion

我正在运行以下 Powershell 脚本,将一系列输出文件连接到一个 CSV 文件中。 whidataXX.htm(其中 xx 是两位数的序列号),创建的文件数量因运行而异。

$metadataPath = "\\ServerPath\foo" 

function concatenateMetadata {
    $cFile = $metadataPath + "whiconcat.csv"
    Clear-Content $cFile
    $metadataFiles = gci $metadataPath
    $iterations = $metadataFiles.Count
    for ($i=0;$i -le $iterations-1;$i++) {
        $iFile = "whidata"+$i+".htm"
        $FileExists = (Test-Path $metadataPath$iFile -PathType Leaf)
        if (!($FileExists))
        {
            break
        }
        elseif ($FileExists)
        {
            Write-Host "Adding " $metadataPath$iFile
            Get-Content $metadataPath$iFile | Out-File $cFile -append
            Write-Host "to" $cfile
        }
    }
} 

whidataXX.htm 文件采用 UTF8 编码,但我的输出文件采用 UTF16 编码。当我在记事本中查看该文件时,它显示正确,但是当我在十六进制编辑器中查看它时,每个字符之间出现十六进制值 00 ,当我将文件拉入 Java 程序进行处理时,文件打印到控制台,并且在字符之间有额外的空格

首先,这对于 PowerShell 来说正常吗?或者源文件中是否有某些内容会导致此问题?

第二,如何解决上述代码中的编码问题?

最佳答案

Out-* cmdlet(如 Out-File)格式化数据,默认格式为 unicode。

您可以向 Out-file 添加 -Encoding 参数:

Get-Content $metadataPath$iFile | Out-File $cFile -Encoding UTF8 -append

或切换到“添加内容”,这不会重新格式化

Get-Content $metadataPath$iFile | Add-Content $cFile 

关于powershell - 为什么 Powershell 文件串联会将 UTF8 转换为 UTF16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388342/

相关文章:

Powershell 脚本 - 脚本 - 我如何禁用它

powershell - 获取位置 :\

unicode - libpcre2 代码单元宽度

php - 转变 ? ?使用 PHP 到 HTML 中的表情符号

powershell - PSObject 和 PSAdapted 之间的差异

powershell - 如何在 Azure Devops 管道中以管理员权限运行 PowerShell 任务

php - 将字符串拆分为带有瑞典字符的单词

php - SELECT 语句不适用于 utf-8

c++ - 为什么 mbstowcs 返回 "invalid multibyte character"

c++ - boost UTF-16 字符串的库?