[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [ValidateSet('Detect', 'Remove', 'Replace')] [string]$Mode = 'Detect', [switch]$Apply, [switch]$Recurse, [string]$OutDir = 'clean-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 } $binaryExtensions = @('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.pdf', '.zip', '.gz', '.7z', '.exe', '.dll', '.mp3', '.mp4', '.docx', '.xlsx') $control = [regex]'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]' $outRoot = [IO.Path]::GetFullPath($OutDir) $results = New-Object System.Collections.Generic.List[object] foreach ($file in $files) { if ($binaryExtensions -contains $file.Extension.ToLowerInvariant()) { continue } try { $text = [IO.File]::ReadAllText($file.FullName, [Text.Encoding]::UTF8) } catch { Write-Warning "Пропуск $($file.FullName): $($_.Exception.Message)" continue } $matches = $control.Matches($text) if ($matches.Count -eq 0) { continue } $codes = @($matches | ForEach-Object { '0x{0:X2}' -f [int][char]$_.Value } | Sort-Object -Unique) $results.Add([pscustomobject]@{ File = $file.FullName Count = $matches.Count Codes = ($codes -join ', ') Action = if ($Apply -and $Mode -ne 'Detect') { $Mode } else { 'ReportOnly' } }) if (-not $Apply -or $Mode -eq 'Detect') { continue } $replacement = if ($Mode -eq 'Replace') { ' ' } else { '' } $cleaned = $control.Replace($text, $replacement) 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]::WriteAllText($destination, $cleaned, (New-Object System.Text.UTF8Encoding($false))) Write-Host "Очищен: $($file.FullName) -> $destination" } if ($results.Count -eq 0) { Write-Host 'Управляющие символы не найдены.' exit 0 } $results | Format-Table -AutoSize Write-Host "Файлов с управляющими символами: $($results.Count)" if (-not $Apply -or $Mode -eq 'Detect') { Write-Host 'Это отчёт. Для записи добавьте -Apply и выберите -Mode Remove или -Mode Replace.' }