oracle

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

Powershell 7.xの場合

以下をGet-FileEncoding-ps7.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
    }

    # PowerShell 7 では Get-Content の代わりに [System.IO.File]::ReadAllBytes を使う方が確実
    try {
        $bytes = [System.IO.File]::ReadAllBytes($Path)
    } catch {
        Write-Output "Failed to read file: $_"
        return
    }

    # 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
    }
    elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
        Write-Output "UTF-16 BE"
        return
    }

    # UTF-8 BOMなし判定(strict)
    $utf8Strict = [System.Text.UTF8Encoding]::new($false, $true)
    try {
        $utf8Strict.GetString($bytes) | Out-Null
        Write-Output "UTF-8 (no BOM)"
        return
    } catch {}

    # Shift_JIS 判定
    try {
        $sjis = [System.Text.Encoding]::GetEncoding("shift_jis")
        $sjis.GetString($bytes) | Out-Null
        Write-Output "Shift_JIS"
        return
    } catch {}

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


    Write-Output "Unknown encoding"
}

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

Version 5.xの場合はこちら

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