[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ArchivePath, [Parameter(Mandatory = $true)] [string]$DestinationPath, [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 (Test-Path -LiteralPath $destFull) { $items = @(Get-ChildItem -LiteralPath $destFull -Force) if ($items.Count -gt 0 -and -not $Force) { throw "Папка не пуста: $destFull. Используйте -Force" } } else { 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 foreach ($entry in $zip.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 '(^|/)\.\.(/|$)') { throw "Небезопасный путь: $($entry.FullName)" } $relative = $name.TrimStart('/') $target = [IO.Path]::GetFullPath((Join-Path $destFull $relative)) if (-not $target.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw "Путь вне папки: $($entry.FullName)" } $isDirectory = ($entry.Name -eq '') -or $relative.EndsWith('/') [void]$plan.Add([pscustomobject]@{ Entry = $entry; Target = $target; IsDirectory = $isDirectory }) } if ($plan.Count -eq 0) { throw "Архив пуст" } foreach ($item in $plan) { if (-not $item.IsDirectory -and (Test-Path -LiteralPath $item.Target) -and -not $Force) { throw "Файл уже существует: $($item.Target)" } } foreach ($item in $plan) { if ($item.IsDirectory) { New-Item -ItemType Directory -Path $item.Target -Force | Out-Null continue } $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) } $files = @($plan | Where-Object { -not $_.IsDirectory }).Count "Распаковано файлов: $files в $destFull" } finally { $zip.Dispose() }