[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ArchivePath, [switch]$KeepTemp ) $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 $tempRoot = Join-Path $env:TEMP ('archives-restore-' + [Guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $tempRoot -Force | Out-Null $tempFull = (Resolve-Path -LiteralPath $tempRoot).Path $prefix = $tempFull if (-not $prefix.EndsWith([string][IO.Path]::DirectorySeparatorChar)) { $prefix += [IO.Path]::DirectorySeparatorChar } function Get-EntryHash([System.IO.Compression.ZipArchiveEntry]$Entry) { $sha = [System.Security.Cryptography.SHA256]::Create() try { $stream = $Entry.Open() try { $bytes = $sha.ComputeHash($stream) return ([BitConverter]::ToString($bytes)).Replace('-', '').ToLowerInvariant() } finally { $stream.Dispose() } } finally { $sha.Dispose() } } $ok = 0 $failed = New-Object System.Collections.ArrayList try { $zip = [IO.Compression.ZipFile]::OpenRead($archiveFull) try { 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)" } if ($entry.Name -eq '' -or $name.EndsWith('/')) { $dir = [IO.Path]::GetFullPath((Join-Path $tempFull $name)) if (-not $dir.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw "Путь вне временной папки: $name" } New-Item -ItemType Directory -Path $dir -Force | Out-Null continue } $target = [IO.Path]::GetFullPath((Join-Path $tempFull $name)) if (-not $target.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw "Путь вне временной папки: $name" } $parent = Split-Path -Parent $target if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true) $archiveHash = Get-EntryHash $entry $fileHash = (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash.ToLowerInvariant() $fileSize = (Get-Item -LiteralPath $target).Length if ($archiveHash -ne $fileHash -or $fileSize -ne $entry.Length) { [void]$failed.Add($name) } else { $ok++ } } } finally { $zip.Dispose() } } finally { if ($KeepTemp) { "Временная папка сохранена: $tempFull" } else { Remove-Item -LiteralPath $tempFull -Recurse -Force -ErrorAction SilentlyContinue } } "Проверено файлов: $ok, ошибок: $($failed.Count)" foreach ($name in $failed) { " ошибка: $name" } if ($failed.Count -gt 0) { exit 1 } exit 0