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 クラスを使用して元のファイル エンコーディングを取得する例を次に示します。CurrentEncoding
この例では、内部の BOM 検出ルーチンの結果に基づいてプロパティが設定されるように、ファイルの最初の 3 バイトを読み取ります。
http://msdn.microsoft.com/en-us/library/9y86s1a9.aspx
detectEncodingFromByteOrderMarks パラメーターは、ストリームの最初の 3 バイトを見てエンコードを検出します。ファイルが適切なバイト オーダー マークで始まる場合、UTF-8、リトル エンディアン Unicode、およびビッグ エンディアン 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