LoginSignup
7
7

More than 5 years have passed since last update.

テキストファイルの文字コードを変換する方法

Posted at

テキストファイルの文字コード(SJIS、UTF8)を変換するコードを書いてみました。

# テキストファイルをUTF8からSJISに変換する。
# inpath - 入力ファイル/ディレクトリ
# outpath - 出力ファイル/ディレクトリ
function U-ConvertTo-SjisFile($inpath, $outpath) {
    #Get-Content $inpath -Encoding UTF8 | Set-Content $outpath -Encoding String
    U-Convert-TextFile $inpath $outpath UTF8 String
}

# テキストファイルをSJISからUTF8(BOM付き)に変換する。
# inpath - 入力ファイル/ディレクトリ
# outpath - 出力ファイル/ディレクトリ
function U-ConvertTo-Utf8File($inpath, $outpath) {
    #Get-Content $inpath -Encoding String | Set-Content $outpath -Encoding UTF8
    U-Convert-TextFile $inpath $outpath String UTF8
}

# テキストファイルの文字コードを変換する。
# inpath - 入力ファイル/ディレクトリ
# outpath - 出力ファイル/ディレクトリ
function U-Convert-TextFile($inpath, $outpath, $inlang, $outlang) {
    if (Test-Path -Path $inpath -PathType Container) {
        # inpathがディレクトリの場合、
        # ディレクトリ配下のファイル/ディレクトリに対して、
        # 処理を繰り返す。
        Get-ChildItem $inpath -Recurse | %{
            if ($_.GetType().Name -eq "FileInfo") {
                #$outfullname = $_.FullName.ToLower().Replace($inpath.ToLower(), $outpath)
                $outfullname = $_.FullName.Replace($inpath, $outpath)
                U-Convert-TextFile $_.FullName $outfullname $inlang $outlang
            }
        }
    } else {
        # inpathがファイルの場合

        # outpathがディレクトリの場合、
        # 入力ファイルと同じファイル名を付加する。
        if (Test-Path -Path $outpath -PathType Container) {
            $outname = Split-Path $inpath -Leaf
            $outpath = Join-Path $outpath $outname
        }

        Write-Debug $inpath
        Write-Debug $outpath

        New-Item $outpath -ItemType file -Force | Out-Null
        Get-Content $inpath -Encoding $inlang | Set-Content $outpath -Encoding $outlang
    }
}
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7