Out-File
除非用参数覆盖,否则具有默认编码-Encoding
:
我为解决这个问题所做的是尝试通过读取尝试读取它的字节顺序标记并将其用作-Encoding
参数值来获取原始文件的编码。
这是一个处理一堆文本文件路径、获取原始编码、处理内容并使用原始编码将其写回文件的示例。
function Get-FileEncoding {
param ( [string] $FilePath )
[byte[]] $byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $FilePath
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ $encoding = 'UTF8' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ $encoding = 'BigEndianUnicode' }
elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe)
{ $encoding = 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ $encoding = 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ $encoding = 'UTF7'}
else
{ $encoding = 'ASCII' }
return $encoding
}
foreach ($textFile in $textFiles) {
$encoding = Get-FileEncoding $textFile
$content = Get-Content -Encoding $encoding
# Process content here...
$content | Set-Content -Path $textFile -Encoding $encoding
}
更新这里是使用 StreamReader 类获取原始文件编码的示例。该示例读取文件的前 3 个字节,以便CurrentEncoding
根据其内部 BOM 检测例程的结果设置属性。
http://msdn.microsoft.com/en-us/library/9y86s1a9.aspx
detectEncodingFromByteOrderMarks 参数通过查看流的前三个字节来检测编码。如果文件以适当的字节顺序标记开头,它会自动识别 UTF-8、little-endian Unicode 和 big-endian Unicode 文本。否则,使用 UTF8Encoding。有关详细信息,请参阅 Encoding.GetPreamble 方法。
http://msdn.microsoft.com/en-us/library/system.text.encoding.getpreamble.aspx
$text = @"
This is
my text file
contents.
"@
#Create text file.
[IO.File]::WriteAllText($filePath, $text, [System.Text.Encoding]::BigEndianUnicode)
#Create a stream reader to get the file's encoding and contents.
$sr = New-Object System.IO.StreamReader($filePath, $true)
[char[]] $buffer = new-object char[] 3
$sr.Read($buffer, 0, 3)
$encoding = $sr.CurrentEncoding
$sr.Close()
#Show the detected encoding.
$encoding
#Update the file contents.
$content = [IO.File]::ReadAllText($filePath, $encoding)
$content2 = $content -replace "my" , "your"
#Save the updated contents to file.
[IO.File]::WriteAllText($filePath, $content2, $encoding)
#Display the result.
Get-Content $filePath