【问题标题】:Using PowerShell to write a file in UTF-8 without the BOM without double encoding使用 PowerShell 以 UTF-8 编写文件,无需 BOM,无需双重编码
【发布时间】:2012-10-25 09:51:00
【问题描述】:

我在这个论坛上看到了几个很棒的解决方案,可以在没有 BOM 的情况下转换为 UTF-8。我需要能够使用 powershell 或类似的递归方式转换一系列文件。

如果我获取 UTF-8 文档并将其转换为 UTF-8,则字符将被双重编码。有没有办法防止这种行为或检测文件是否已经是没有 BOM 的 UTF-8?

foreach($i in ls -recurse -filter "*.*") {
    if (
        $i.Extension.ToLower() -eq ".html" -or 
        $i.Extension.ToLower() -eq ".htm" -or 
        $i.Extension.ToLower() -eq ".php" -or 
        $i.Extension.ToLower() -eq ".txt"
    ) {
        $MyFile = Get-Content $i.fullname 
        [System.IO.File]::WriteAllLines($i.fullname, $MyFile)
    }
}

【问题讨论】:

    标签: powershell encoding recursion utf-8 byte-order-mark


    【解决方案1】:

    您可以向Get-Content 提供编码:

    Get-Content $i.FullName -Encoding UTF8
    

    【讨论】:

    • 如果我不知道编码怎么办。我们可能有一些已经编码为 UTF-8 的文件。第一次通过的大部分将是 ANSI (Windows)。
    猜你喜欢
    • 2016-02-29
    • 1970-01-01
    • 2020-05-08
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    相关资源
    最近更新 更多