[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ArchivePath, [Parameter(Mandatory = $true)] [string]$Pattern, [Parameter(Mandatory = $true)] [string]$DestinationPath, [switch]$Flatten, [switch]$Force ) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.IO.Compression.FileSystem if (-not (Test-Path -LiteralPath $ArchivePath -PathType Leaf)) { throw "Архив не найден: $ArchivePath" } $archiveFull = (Resolve-Path -LiteralPath $ArchivePath).Path $destFull = [IO.Path]::GetFullPath($DestinationPath) if (Test-Path -LiteralPath $destFull -PathType Leaf) { throw "Цель является файлом: $destFull" } if (-not (Test-Path -LiteralPath $destFull)) { New-Item -ItemType Directory -Path $destFull -Force | Out-Null } $prefix = $destFull if (-not $prefix.EndsWith([string][IO.Path]::DirectorySeparatorChar)) { $prefix += [IO.Path]::DirectorySeparatorChar } $zip = [IO.Compression.ZipFile]::OpenRead($archiveFull) try { $plan = New-Object System.Collections.ArrayList $seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) foreach ($entry in $zip.Entries) { $name = $entry.FullName.Replace('\', '/') if ([string]::IsNullOrWhiteSpace($name) -or $name.EndsWith('/')) { continue } if (-not ($name -like $Pattern -or $entry.Name -like $Pattern)) { continue } if ($name.StartsWith('/') -or $name -match '^[A-Za-z]:' -or $name.Contains(':') -or $name -match '(^|/)\.\.(/|$)') { throw "Небезопасный путь: $($entry.FullName)" } $relative = if ($Flatten) { $entry.Name } else { $name } $target = [IO.Path]::GetFullPath((Join-Path $destFull $relative)) if (-not $target.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw "Путь вне папки: $($entry.FullName)" } if (-not $seen.Add($target)) { throw "После уплощения имена совпадают: $relative" } if ((Test-Path -LiteralPath $target) -and -not $Force) { throw "Файл уже существует: $target" } [void]$plan.Add([pscustomobject]@{ Entry = $entry; Target = $target }) } if ($plan.Count -eq 0) { throw "Под маску $Pattern ничего не подошло" } foreach ($item in $plan) { $parent = Split-Path -Parent $item.Target if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } [IO.Compression.ZipFileExtensions]::ExtractToFile($item.Entry, $item.Target, [bool]$Force) } "Извлечено файлов: $($plan.Count) в $destFull" } finally { $zip.Dispose() }