【问题标题】:Convert UTF-8 to ANSI将 UTF-8 转换为 ANSI
【发布时间】:2017-08-22 23:11:21
【问题描述】:

我正在尝试将 UTF-8 转换为 ANSI 文件。在谷歌的一点点知识和帮助下,我找到了一行来转换 SINGLE 文件

Get-Content C:\Output2\PA01.094 | Set-Content C:\Output\PA01094 -Encoding Ascii

现在我想将一个文件夹中的所有 UTF-8 文件转换到另一个文件夹而不更改文件名。

【问题讨论】:

    标签: powershell character-encoding


    【解决方案1】:

    以下将读取$sourceFolder中的所有文件,并在$destFolder下重新创建它们,编码为ASCII。

    $sourceFolder = "c:\temp\src"
    $destFolder = "c:\temp\dst"
    
    Get-ChildItem -Path $sourceFolder | 
        foreach-object {
            get-content $_ | Set-content -Path ( Join-Path $destFolder $_.Name ) -Encoding ASCII
        }
    

    注意此代码不验证原始文件的编码。

    【讨论】:

      【解决方案2】:

      您可以使用如下代码。根据需要修改Get-ChildItem,指定你需要的文件。

      $sourcePath = "C:\source"
      $destinationPath = "C:\output"
      if (!(Test-Path $destinationPath))
      {
          New-Item -ItemType Directory -Path $destinationPath
      }
      Get-ChildItem -Path $sourcePath -File | ForEach-Object {
       Write-Host "Converting $_" 
       $content = Get-Content $_.FullName
       Set-content (Join-Path -Path $destinationPath -ChildPath $_) -Encoding Ascii -Value $content
      }
      

      ASCII 编码无法处理 UTF8 或其他 Unicode 编码可以处理的所有字符,无法翻译的字符可能会导致 ?在输出文件中。

      要检查输出的编码,您可以使用 PowerShell。

      例如,在记事本中创建的文本文件显示“Hello, World!”

      以下编码将产生这些结果。注意UTF-8开头有特殊字符,表示文件是UTF-8,不是记事本默认的保存格式。

      PS C:\support> [System.IO.File]::ReadAllBytes("C:\support\helloworld_ansi.txt")
          72
          101
          108
          108
          111
          44
          32
          87
          111
          114
          108
          100
          33
          PS C:\support> [System.IO.File]::ReadAllBytes("C:\support\helloworld_unicode.txt")
          255
          254
          72
          0
          101
          0
          108
          0
          108
          0
          111
          0
          44
          0
          32
          0
          87
          0
          111
          0
          114
          0
          108
          0
          100
          0
          33
          0
          PS C:\support> [System.IO.File]::ReadAllBytes("C:\support\helloworld_utf8.txt")
          239
          187
          191
          72
          101
          108
          108
          111
          44
          32
          87
          111
          114
          108
          100
          33
          PS C:\support>
      

      【讨论】:

      • 这将覆盖原始文件。请求是将文件写入另一个文件夹。
      • 将设置内容更改为您要写入文件的任何位置,添加示例
      • 有点厚脸皮。您最初的答案错过了问题的重点。当我指出这一点时,你会扯掉我的答案。不错。
      • 我什至没有看到你的答案,我误读了这个问题,我最初认为它说要覆盖现有文件。我仍然打开页面。
      • 感谢所有脚本运行并将文件放入目标文件夹但不转换文件
      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 2015-10-06
      • 2013-12-14
      • 2012-01-08
      • 2015-11-22
      • 2013-02-11
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多