Files

248 lines
13 KiB
PowerShell
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Завершает переразметку USB: проверяет MBR/gap, возвращает файлы на p1/p2/p3.
.DESCRIPTION
Нужен, если relayout-usb.ps1 упал после diskpart (например, на Close()
дескриптора PhysicalDrive) и файлы не были возвращены.
Скрипт:
1. проверяет геометрию: p1 14 ГиБ @1 МиБ active, p2 32 МиБ сразу за p1,
p3 = остаток;
2. сверяет байты 0..445 MBR и gap-сектора 1..62 с бэкапом
C:\PF\Ventoy\backup\usb-mbr-*.bin и при необходимости возвращает их;
3. копирует staging (E:\_usb_stage\PARAVIS) на p1;
4. ставит VTOYEFI + core на p2;
5. копирует ISO с E:\Downloads\ISO на p3 и \ISO\Ventoy (маркер);
6. сверяет размеры/количество.
.EXAMPLE
.\finish-relayout.ps1 -WhatIf
.\finish-relayout.ps1
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[int]$BootSizeMB = 14336,
[string]$StageDir = 'E:\_usb_stage',
[string]$IsoSource = 'E:\Downloads\ISO',
[string]$VentoyDir = 'C:\PF\Ventoy',
[string]$BackupDir = 'C:\PF\Ventoy\backup',
[switch]$SkipMbr
)
$ErrorActionPreference = 'Stop'
function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan }
function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green }
function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow }
function Invoke-Robocopy([string]$src, [string]$dst, [string[]]$extra = @()) {
$roboArgs = @($src, $dst, '/E', '/COPY:DAT', '/R:1', '/W:1', '/MT:8', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') + $extra
$out = & robocopy.exe @roboArgs 2>&1
$code = $LASTEXITCODE
if ($code -ge 8) {
$out | Select-Object -Last 30 | ForEach-Object { " $_" }
throw "robocopy вернул код $code ($src -> $dst)"
}
return $code
}
function Get-DiskVolumeLabel([int]$num, [string]$label) {
foreach ($p in (Get-Partition -DiskNumber $num -ErrorAction SilentlyContinue)) {
$v = Get-Volume -Partition $p -ErrorAction SilentlyContinue
if ($v -and $v.FileSystemLabel -eq $label) { return $v }
}
return $null
}
function Read-Raw([int]$num, [int]$len) {
$fs = [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)
try {
$buf = New-Object byte[] $len
$n = $fs.Read($buf, 0, $len)
if ($n -ne $len) { throw "Прочитано $n из $len байт." }
return ,$buf
} finally {
try { $fs.Close() } catch { }
}
}
function Write-Raw([int]$num, [byte[]]$data, [long]$offset) {
$fs = [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite, 4096, [IO.FileOptions]::WriteThrough)
try {
$fs.Position = $offset
$fs.Write($data, 0, $data.Length)
$fs.Flush($true)
} finally {
# Windows может инвалидировать хэндл после записи в сектор 0 —
# ошибка Close() не означает, что запись не выполнена.
try { $fs.Close() } catch { }
}
}
function Test-Range([byte[]]$a, [byte[]]$b, [int]$offset, [int]$count) {
for ($i = 0; $i -lt $count; $i++) {
if ($a[$offset + $i] -ne $b[$offset + $i]) { return $false }
}
return $true
}
# ------------------------------------------------------------------ диск
Write-Step "Поиск диска"
$efiVol = Get-Volume | Where-Object { $_.FileSystemLabel -eq 'VTOYEFI' } | Select-Object -First 1
if (-not $efiVol -or -not $efiVol.DriveLetter) { throw "Не найден раздел VTOYEFI." }
$diskNum = (Get-Partition -DriveLetter $efiVol.DriveLetter).DiskNumber
$disk = Get-Disk -Number $diskNum
Write-Host (" Диск {0}: {1}, {2:N1} ГиБ, {3}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle)
$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$pData = Get-DiskVolumeLabel $diskNum 'DATA'
if (-not $pProj -or -not $pEfi -or -not $pData) { throw "Не найдены все три раздела (PARAVIS/VTOYEFI/DATA)." }
Write-Host (" PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter)
# ------------------------------------------------------------- геометрия
Write-Step "Проверка геометрии"
$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset
$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host
if ($geo.Count -ne 3) { throw "Ожидалось 3 раздела, найдено $($geo.Count)." }
if ($geo[0].Offset -ne 1048576) { throw "p1 начинается не с 1 МиБ (Offset=$($geo[0].Offset))." }
if ($geo[0].Size -ne ($BootSizeMB * 1MB)) { throw "p1 неверного размера: $($geo[0].Size)." }
if ($geo[1].Offset -ne ($geo[0].Offset + $geo[0].Size)) { throw "p2 идёт не сразу за p1." }
if ($geo[1].Size -ne 33554432) { throw "p2 не 32 МБ: $($geo[1].Size)." }
if (-not $geo[0].IsActive) { throw "p1 не помечен active." }
Write-Ok "Геометрия корректна."
# ---------------------------------------------------------------- MBR/gap
if ($SkipMbr) {
Write-Step "Проверка MBR пропущена (-SkipMbr)"
} else {
Write-Step "Проверка MBR Xorboot и gap-секторов"
$bkp = Get-ChildItem $BackupDir -Filter 'usb-mbr-*.bin' | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not $bkp) { throw "Нет бэкапа MBR в $BackupDir." }
Write-Host (" бэкап: {0}" -f $bkp.FullName)
if ($bkp.Length -lt 65536) { throw "Бэкап короче 64 КиБ." }
$orig = [IO.File]::ReadAllBytes($bkp.FullName)
$cur = Read-Raw $diskNum 65536
$mbrOk = Test-Range $cur $orig 0 446
$gapOk = Test-Range $cur $orig 512 31744
Write-Host (" MBR code (0..445): {0}" -f $(if ($mbrOk) { 'совпадает с бэкапом' } else { 'ОТЛИЧАЕТСЯ' }))
Write-Host (" gap (сектора 1..62): {0}" -f $(if ($gapOk) { 'совпадает с бэкапом' } else { 'ОТЛИЧАЕТСЯ' }))
if (-not $mbrOk -or -not $gapOk) {
if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum", "Восстановить код MBR (0..445) и gap (512..32255) из бэкапа")) {
Write-Warn "WhatIf: MBR не изменялся."
} else {
if (-not $mbrOk) {
$buf = New-Object byte[] 446
[Array]::Copy($orig, 0, $buf, 0, 446)
Write-Raw $diskNum $buf 0
Write-Ok "Код MBR (0..445) восстановлен."
}
if (-not $gapOk) {
$buf = New-Object byte[] 31744
[Array]::Copy($orig, 512, $buf, 0, 31744)
Write-Raw $diskNum $buf 512
Write-Ok "Gap (сектора 1..62) восстановлен."
}
Start-Sleep -Seconds 2
Update-HostStorageCache
$cur2 = Read-Raw $diskNum 65536
if (-not (Test-Range $cur2 $orig 0 446)) { throw "MBR после записи не совпал с бэкапом." }
if (-not (Test-Range $cur2 $orig 512 31744)) { throw "Gap после записи не совпал с бэкапом." }
Write-Ok "MBR и gap совпадают с бэкапом."
}
} else {
Write-Ok "MBR и gap уже в порядке (запись Xorboot выполнена)."
}
}
# --------------------------------------------------------------- источники
Write-Step "Обновление букв после проверки MBR"
Update-HostStorageCache
Start-Sleep -Seconds 1
$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$pData = Get-DiskVolumeLabel $diskNum 'DATA'
if (-not $pProj -or -not $pEfi -or -not $pData) { throw "Разделы пропали после работы с MBR." }
if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) {
foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) {
Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter
}
Start-Sleep -Seconds 1
$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$pData = Get-DiskVolumeLabel $diskNum 'DATA'
}
Write-Host (" PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter)
Write-Step "Проверка источников"
$stageProj = Join-Path $StageDir 'PARAVIS'
$stageIsoVentoy = Join-Path $StageDir 'ISO_Ventoy'
$vtoyefi = Join-Path $VentoyDir 'vtoyefi'
$coreImg = Join-Path $VentoyDir 'core-custom-layout-1.1.18.img'
if (-not (Test-Path $stageProj)) { throw "Нет staging: $stageProj" }
if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Нет VTOYEFI: $vtoyefi" }
if (-not (Test-Path $coreImg)) { throw "Нет core: $coreImg" }
if (-not (Test-Path $IsoSource)) { throw "Нет ISO: $IsoSource" }
$isos = Get-ChildItem $IsoSource -File -Filter *.iso
$isoBytes = ($isos | Measure-Object Length -Sum).Sum
$projBytes = (Get-ChildItem $stageProj -Recurse -File -Force | Measure-Object Length -Sum).Sum
Write-Host (" проект: {0:N2} ГБ, ISO: {1} шт. / {2:N2} ГБ" -f ($projBytes/1GB), $isos.Count, ($isoBytes/1GB))
if ($pProj.SizeRemaining -lt $projBytes) { throw "На p1 не хватает места." }
if ($pData.SizeRemaining -lt $isoBytes) { throw "На p3 не хватает места." }
if (-not $PSCmdlet.ShouldProcess("${pProj.DriveLetter}: / ${pEfi.DriveLetter}: / ${pData.DriveLetter}:", "Вернуть проект, VTOYEFI и ISO")) {
Write-Warn "WhatIf: файлы не копировались."
return
}
# ---------------------------------------------------------------- restore
Write-Step "Возврат проекта на p1"
Invoke-Robocopy $stageProj ("{0}:\" -f $pProj.DriveLetter) | Out-Null
Write-Ok "Проект восстановлен."
Write-Step "VTOYEFI на p2"
Invoke-Robocopy $vtoyefi ("{0}:\" -f $pEfi.DriveLetter) | Out-Null
Copy-Item $coreImg ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter) -Force
if (-not (Select-String -Path ("{0}:\grub\grub.cfg" -f $pEfi.DriveLetter) -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) {
throw "На p2 grub.cfg без VTOY-CUSTOM-LAYOUT."
}
if ((Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length -ne (Get-Item $coreImg).Length) {
throw "core.img на p2 неверного размера."
}
Write-Ok ("VTOYEFI + core ({0} Б)." -f (Get-Item $coreImg).Length)
Write-Step "ISO и \ISO\Ventoy на p3"
Invoke-Robocopy $IsoSource ("{0}:\ISO" -f $pData.DriveLetter) | Out-Null
if (Test-Path $stageIsoVentoy) {
Invoke-Robocopy $stageIsoVentoy ("{0}:\ISO\Ventoy" -f $pData.DriveLetter) | Out-Null
} else {
New-Item -ItemType Directory -Force -Path ("{0}:\ISO\Ventoy\theme" -f $pData.DriveLetter) | Out-Null
[IO.File]::WriteAllText(("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter), "Ventoy data partition marker`r`nDo not delete this file.`r`n")
}
if (-not (Test-Path ("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter))) { throw "Маркер NOT.DEL не создан." }
Write-Ok "ISO и маркер на месте."
# ---------------------------------------------------------------- verify
Write-Step "Проверка результата"
$isoDst = Get-ChildItem ("{0}:\ISO" -f $pData.DriveLetter) -File -Filter *.iso
$isoDstBytes = ($isoDst | Measure-Object Length -Sum).Sum
$projDst = Get-ChildItem ("{0}:\" -f $pProj.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\System Volume Information\\' -and $_.FullName -notmatch '\\\$RECYCLE\.BIN\\' } |
Measure-Object Length -Sum
" ISO на p3: {0} шт., {1:N2} ГБ (источник {2:N2} ГБ)" -f $isoDst.Count, ($isoDstBytes/1GB), ($isoBytes/1GB)
" проект на p1: {0} файлов, {1:N2} ГБ (источник {2:N2} ГБ)" -f $projDst.Count, ($projDst.Sum/1GB), ($projBytes/1GB)
" core.img: {0} Б" -f (Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length
if ($isoDst.Count -ne $isos.Count -or $isoDstBytes -ne $isoBytes) { Write-Warn "ISO: количество/размер не совпал!" }
if ($projDst.Sum -ne $projBytes) { Write-Warn "Проект: размер не совпал!" }
Write-Step "Готово"
Write-Host "Проверяйте загрузку Xorboot -> Ventoy." -ForegroundColor Green
Write-Host "Если Xorboot не грузится — Change_bootLoader.exe -> Install XorBoot." -ForegroundColor Green