我正在尝试将UTF-8转换为ANSI文件。通过一些了解和谷歌的帮助,我找到了一行代码可以将单个文件进行转换。
Get-Content C:\Output2\PA01.094 | Set-Content C:\Output\PA01094 -Encoding Ascii
现在我想将一个文件夹中的所有UTF-8文件转换到另一个文件夹,而不更改文件名。
我正在尝试将UTF-8转换为ANSI文件。通过一些了解和谷歌的帮助,我找到了一行代码可以将单个文件进行转换。
Get-Content C:\Output2\PA01.094 | Set-Content C:\Output\PA01094 -Encoding Ascii
$sourceFolder
中的所有文件,并将它们重新创建到$destFolder
下,编码为ASCII。$sourceFolder = "c:\temp\src"
$destFolder = "c:\temp\dst"
Get-ChildItem -Path $sourceFolder |
foreach-object {
get-content $_.FullName | Set-content -Path ( Join-Path $destFolder $_.Name ) -Encoding ASCII
}
注意:此代码不验证原始文件的编码。
$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>