[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [switch]$Convert, [string]$Suffix = '.utf8' ) $ErrorActionPreference = 'Stop' $resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop $files = Get-ChildItem -LiteralPath $resolved -File -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Extension -in '.srt', '.vtt', '.ass', '.ssa' } if (-not $files) { Write-Host 'Файлы субтитров не найдены.' exit 0 } $utf8Strict = [System.Text.UTF8Encoding]::new($false, $true) $cp1251 = [System.Text.Encoding]::GetEncoding(1251) $rows = foreach ($file in $files) { $bytes = [System.IO.File]::ReadAllBytes($file.FullName) $encoding = 'unknown' if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $encoding = 'utf-8-bom' } elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) { $encoding = 'utf-16-le' } elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) { $encoding = 'utf-16-be' } else { try { [void]$utf8Strict.GetString($bytes) $encoding = 'utf-8' } catch { $encoding = 'windows-1251' } } [pscustomobject]@{ File = $file.FullName Encoding = $encoding Bytes = $bytes.Length } } $rows | Format-Table -AutoSize -Wrap if ($Convert) { foreach ($row in $rows | Where-Object { $_.Encoding -ne 'utf-8' }) { $file = Get-Item -LiteralPath $row.File $bytes = [System.IO.File]::ReadAllBytes($file.FullName) $text = $null if ($row.Encoding -eq 'windows-1251') { $text = $cp1251.GetString($bytes) } elseif ($row.Encoding -eq 'utf-8-bom') { $text = [System.Text.Encoding]::UTF8.GetString($bytes).TrimStart([char]0xFEFF) } elseif ($row.Encoding -eq 'utf-16-le') { $text = [System.Text.Encoding]::Unicode.GetString($bytes) } elseif ($row.Encoding -eq 'utf-16-be') { $text = [System.Text.Encoding]::BigEndianUnicode.GetString($bytes) } else { Write-Warning "Пропуск $($file.FullName): кодировка не определена" continue } $target = Join-Path $file.DirectoryName ($file.BaseName + $Suffix + $file.Extension) if (Test-Path -LiteralPath $target) { Write-Warning "Уже существует: $target" continue } [System.IO.File]::WriteAllText($target, $text, [System.Text.UTF8Encoding]::new($false)) Write-Host "Сохранено: $target" } }