oracle

Powershell 5.xでファイルの文字コードを判定する

Powershell version 5.x の場合

以下をGet-FileEncoding-ps5.ps1というファイル名で作成します。(ファイル名はお好みでどうぞ)

param (
    [Parameter(Mandatory = $true)]
    [string]$Path
)

function Get-FileEncoding {
    param (
        [string]$Path
    )

    if (-not (Test-Path $Path)) {
        Write-Output "File not found: $Path"
        return
    }

    $bytes = Get-Content -Encoding Byte -ReadCount 0 -Path $Path

    # BOMチェック
    if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
        Write-Output "UTF-8 with BOM"
        return
    }
    elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
        Write-Output "UTF-16 LE"
        return
    }
    # UTF-16 BE BOMなしもありえるがShift_JISとの区別をつけるのが難しい
    elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
        Write-Output "UTF-16 BE"
        return
    }

    # UTF-8 BOM無しを試みる
    $utf8Strict = New-Object System.Text.UTF8Encoding($false, $true) # throwOnInvalidBytes: true
    try {
        $utf8Strict.GetString($bytes) | Out-Null
        Write-Output "UTF-8 (no BOM)"
        return
    }catch {}

    # EUC-JP を試みる
    try {
        $eucjp = [System.Text.Encoding]::GetEncoding("euc-jp")
        $eucjp.GetString($bytes) | Out-Null
        Write-Output "EUC-JP"
        return
    } catch {}

    # Shift-JIS を試みる
    try {
        $sjis = [System.Text.Encoding]::GetEncoding("shift_jis")
        $sjis.GetString($bytes) | Out-Null
        Write-Output "Shift_JIS"
        return
    } catch {}

    # その他不明
    Write-Output "Unknown encoding"
}

# --- 関数呼び出し ---
Get-FileEncoding $Path

Version 7.xの場合はこちら

スポンサーリンク
タイトルとURLをコピーしました