PowerShellで空行削除を途中で入れようとしたら、Encodelingは最後に行わないと文字化けした。。。。
理由は分からないけど、文字列置換だけなら大丈夫だったけど、空行削除してエンコード保存するとエラーになったから、
とりあえずそのまま保存して、最後にエンコードしたら、文字化けしなかった。
$test = (Get-Content C:\テスト\テスト.txt)
【文字化けするコード】
# 文字列置換
$file_contents = $test -replace [regex]::Escape("\\test\test1\"), "\\test2\test2\"
$file_contents | Set-Content ".\テスト_enc.txt" -Encoding String
# 空行の削除
$file_contents = Select-String -Pattern "\S" ".\テスト_enc.txt" | %{$_.line}
$file_contents | Set-Content ".\テスト_enc.txt" -Encoding String
echo (Get-Content ".\テスト_enc.txt")
【文字化けしないコード】
# 文字列置換
$file_contents = $test -replace [regex]::Escape("\\test\test1\"), "\\test2\test2\"
$file_contents > ".\テスト_enc.txt"
# 空行の削除
$file_contents = Select-String -Pattern "\S" ".\テスト_enc.txt" | %{$_.line}
$file_contents > ".\テスト_enc.txt"
$file_contents | Set-Content ".\テスト_enc.txt" -Encoding String
echo (Get-Content ".\テスト_enc.txt")
【実行結果】
・文字化けするコードの場合
?e?X?g?@
\\test2\test2\test.txt
・文字化けしないコードの場合
テスト①
\\test2\test2\test.txt
――【もともとのファイルの中身】―――テスト.txt
テスト①
\\test\test1\test.txt
―――――――――――――――――――テスト.txt