Проверить и убрать BOM
Находит UTF-8 BOM в файлах, умеет добавлять его и удалять, сохраняя копии отдельно.
Что делает скрипт
Скрипт читает первые байты файла и определяет наличие метки порядка байтов. В режиме Detect показывается только отчёт, в режимах Add и Remove результат пишется в папку bom-out. Для правки на месте нужен флаг -InPlace, который создаёт файл .bak.
- Режим -InPlace меняет исходные файлы, но оставляет копии .bak.
Быстрый старт
powershell -File Bom-Tool.ps1 -Path C:\Docs -Mode Detect -Recurse
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Bom-Tool.ps1 -Path .\docs -Mode Detect -Recursepowershell -File Bom-Tool.ps1 -Path .\docs -Mode Remove -Recurse -OutDir cleanpowershell -File Bom-Tool.ps1 -Path .\notes.txt -Mode Add -InPlace
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Bom-Tool.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[ValidateSet('Detect', 'Add', 'Remove')]
[string]$Mode = 'Detect',
[switch]$Recurse,
[string]$OutDir = 'bom-out',
[switch]$InPlace
)
$ErrorActionPreference = 'Stop'
$item = Get-Item -LiteralPath $Path -ErrorAction Stop
if ($item.PSIsContainer) {
$files = Get-ChildItem -LiteralPath $item.FullName -File -Recurse:$Recurse -ErrorAction SilentlyContinue
$base = $item.FullName
} else {
$files = @($item)
$base = $item.Directory.FullName
}
if ($Mode -ne 'Detect' -and $InPlace -and $item.PSIsContainer -and -not $Recurse) {
Write-Host 'Для папки без -Recurse обрабатываются только файлы верхнего уровня.'
}
$bom = [byte[]](0xEF, 0xBB, 0xBF)
$outRoot = [IO.Path]::GetFullPath($OutDir)
$results = New-Object System.Collections.Generic.List[object]
foreach ($file in $files) {
$bytes = [IO.File]::ReadAllBytes($file.FullName)
$hasBom = $bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF
if ($Mode -eq 'Detect') {
$results.Add([pscustomobject]@{
File = $file.FullName
HasBom = $hasBom
Size = $bytes.Length
})
continue
}
if ($Mode -eq 'Add' -and $hasBom) { continue }
if ($Mode -eq 'Remove' -and -not $hasBom) { continue }
if ($Mode -eq 'Add') {
$newBytes = [byte[]]($bom + $bytes)
} elseif ($bytes.Length -eq 3) {
$newBytes = [byte[]]@()
} else {
$newBytes = [byte[]]$bytes[3..($bytes.Length - 1)]
}
if ($InPlace) {
$backup = $file.FullName + '.bak'
Copy-Item -LiteralPath $file.FullName -Destination $backup -Force
$destination = $file.FullName
} else {
$relative = $file.FullName.Substring($base.Length).TrimStart('\', '/')
$destination = Join-Path $outRoot $relative
$parent = Split-Path -Parent $destination
if ($parent) { [IO.Directory]::CreateDirectory($parent) | Out-Null }
}
if (-not $InPlace -and [IO.Path]::GetFullPath($destination) -eq $file.FullName) {
Write-Warning "Пропуск, выходной путь совпадает с входным: $($file.FullName)"
continue
}
[IO.File]::WriteAllBytes($destination, $newBytes)
Write-Host "$Mode : $($file.FullName) -> $destination"
}
if ($Mode -eq 'Detect') {
$results | Format-Table -AutoSize
$withBom = @($results | Where-Object { $_.HasBom }).Count
Write-Host "Файлов с BOM: $withBom из $($results.Count)"
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.