[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)" }