将 UTF-8 转换为 ANSI



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

Get-Content C:Output2PA01.094 | Set-Content C:OutputPA01094 -Encoding Ascii

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

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

$sourceFolder = "c:tempsrc"
$destFolder = "c:tempdst"
Get-ChildItem -Path $sourceFolder | 
foreach-object {
get-content $_.FullName | Set-content -Path ( Join-Path $destFolder $_.Name ) -Encoding ASCII
}

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

您可以使用如下代码。根据需要修改 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。

例如,在记事本中创建的文本文件显示"你好,世界!

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

PS C:support> [System.IO.File]::ReadAllBytes("C:supporthelloworld_ansi.txt")
72
101
108
108
111
44
32
87
111
114
108
100
33
PS C:support> [System.IO.File]::ReadAllBytes("C:supporthelloworld_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:supporthelloworld_utf8.txt")
239
187
191
72
101
108
108
111
44
32
87
111
114
108
100
33
PS C:support>

最新更新