[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$InputPath, [Parameter(Mandatory = $true)] [string]$OutputPath, [ValidateSet('Optimal', 'Fastest', 'NoCompression')] [string]$CompressionLevel = 'Optimal', [string[]]$Exclude = @(), [switch]$Force ) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.IO.Compression.FileSystem if (-not (Test-Path -LiteralPath $InputPath -PathType Leaf)) { throw "Архив не найден: $InputPath" } $inputFull = (Resolve-Path -LiteralPath $InputPath).Path $outputFull = [IO.Path]::GetFullPath($OutputPath) if ($inputFull -eq $outputFull) { throw "Вход и выход совпадают" } if (Test-Path -LiteralPath $outputFull) { if (-not $Force) { throw "Файл уже существует: $outputFull. Используйте -Force" } Remove-Item -LiteralPath $outputFull -Force } $parent = Split-Path -Parent $outputFull if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } $level = [System.Enum]::Parse([System.IO.Compression.CompressionLevel], $CompressionLevel) $source = [IO.Compression.ZipFile]::OpenRead($inputFull) $stream = [IO.File]::Open($outputFull, [IO.FileMode]::CreateNew) $target = [System.IO.Compression.ZipArchive]::new($stream, [System.IO.Compression.ZipArchiveMode]::Create) $copied = 0 $skipped = 0 try { foreach ($entry in $source.Entries) { $name = $entry.FullName.Replace('\', '/') if ([string]::IsNullOrWhiteSpace($name)) { continue } if ($name.StartsWith('/') -or $name -match '^[A-Za-z]:' -or $name.Contains(':') -or $name -match '(^|/)\.\.(/|$)') { Write-Warning "Пропуск небезопасного пути: $($entry.FullName)" $skipped++ continue } $excluded = $false foreach ($pattern in $Exclude) { if ($name -like $pattern -or $entry.Name -like $pattern) { $excluded = $true break } } if ($excluded) { $skipped++ continue } $newEntry = $target.CreateEntry($name, $level) $newEntry.LastWriteTime = $entry.LastWriteTime if ($entry.Name -eq '' -or $name.EndsWith('/')) { $copied++ continue } $input = $entry.Open() try { $output = $newEntry.Open() try { $input.CopyTo($output) } finally { $output.Dispose() } } finally { $input.Dispose() } $copied++ } } finally { $target.Dispose() $stream.Dispose() $source.Dispose() } "Перенесено элементов: $copied, пропущено: $skipped" "Готово: $outputFull"