Files
Ventoy/build-scripts/layout/restore-ventoy-p2.ps1

121 lines
6.0 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
Восстанавливает VTOYEFI (p2) из C:\PF\Ventoy без изменения разделов и MBR.
.DESCRIPTION
Копирует полный VTOYEFI 1.1.18 (с кастомным grub.cfg: раздел с ISO
определяется по маркеру /ISO/Ventoy/NOT.DEL) и патченный core.img
(409 448 Б: MBR check и geometry check отключены, номер раздела данных
берётся из VTOY_DATA_PART_IDX). Полезно, если p2 очищен или нужно
вернуть рабочую конфигурацию после экспериментов.
.PARAMETER DriveLetter
Буква раздела VTOYEFI. По умолчанию G.
.PARAMETER SourceDir
Папка C:\PF\Ventoy.
.PARAMETER CoreImg
Патченный core. По умолчанию core-custom-layout-1.1.18.img.
.PARAMETER Force
Не проверять метку VTOYEFI.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
[char]$DriveLetter = 'G',
[string]$SourceDir = 'C:\PF\Ventoy',
[string]$CoreImg = '',
[switch]$Force
)
$ErrorActionPreference = 'Stop'
function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan }
function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow }
function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green }
$vtoyefi = Join-Path $SourceDir 'vtoyefi'
if (-not $CoreImg) { $CoreImg = Join-Path $SourceDir 'core-custom-layout-1.1.18.img' }
if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Не найден VTOYEFI: $vtoyefi" }
if (-not (Test-Path $CoreImg)) { throw "Не найден core: $CoreImg" }
Write-Step "Проверка раздела ${DriveLetter}:"
try {
$vol = Get-Volume -DriveLetter $DriveLetter -ErrorAction Stop
} catch {
throw "Раздел ${DriveLetter}: не найден. Если диск offline/readonly — отключите USB от VMware или выключите VM, затем повторите."
}
if (-not $Force -and $vol.FileSystemLabel -ne 'VTOYEFI') {
throw "Метка раздела '$($vol.FileSystemLabel)', а не VTOYEFI. Если уверены — используйте -Force."
}
if ($vol.FileSystem -notmatch 'FAT') { throw "Раздел ${DriveLetter}: не FAT." }
$free = (Get-ChildItem -Recurse -File $vtoyefi | Measure-Object Length -Sum).Sum + (Get-Item $CoreImg).Length
Write-Host ("Нужно ~{0:N1} МБ, свободно {1:N1} МБ" -f ($free/1MB), ($vol.SizeRemaining/1MB))
if ($vol.SizeRemaining -lt $free) { throw "На разделе недостаточно места." }
if (-not $PSCmdlet.ShouldProcess("${DriveLetter}:", "Очистить VTOYEFI и скопировать Ventoy 1.1.18 + патченный core")) {
Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow
return
}
Write-Step "Очистка ${DriveLetter}:"
Get-ChildItem -Force "${DriveLetter}:\" | Remove-Item -Recurse -Force -ErrorAction Stop
Write-Ok "Очищено."
Write-Step "Копирование VTOYEFI 1.1.18"
Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "${DriveLetter}:\" -Recurse -Force -ErrorAction Stop
if (-not (Test-Path "${DriveLetter}:\ventoy\ventoy.cpio")) { throw "Копирование VTOYEFI не удалось." }
Write-Ok "VTOYEFI скопирован."
Write-Step "Копирование патченного core"
Copy-Item -Path $CoreImg -Destination "${DriveLetter}:\ventoy\core.img" -Force -ErrorAction Stop
Write-Ok ("core.img -> {0}:\ventoy\core.img ({1} Б)" -f $DriveLetter, (Get-Item $CoreImg).Length)
Write-Step "Проверка кастомного grub.cfg"
$cfgPath = "${DriveLetter}:\grub\grub.cfg"
if ((Get-Content -Path $cfgPath -Raw -ErrorAction SilentlyContinue) -match 'VTOY-CUSTOM-LAYOUT') {
Write-Ok "grub.cfg: поиск раздела ISO по маркеру /ISO/Ventoy/NOT.DEL включён."
} else {
Write-Warn "grub.cfg без кастомного поиска раздела — Ventoy будет искать ISO на p1."
}
if (-not (Test-Path "${DriveLetter}:\grub\grub.cfg.orig")) {
Write-Warn "Резервная копия grub.cfg.orig на разделе отсутствует (не критично)."
}
Write-Step "Проверка патча vtoyjump (MBR check в PE)"
function Test-ByteAt([string]$Path, [long]$Offset, [byte[]]$Expected) {
if (-not (Test-Path $Path)) { return $false }
$fs = [IO.File]::OpenRead($Path)
try {
$fs.Position = $Offset
$buf = New-Object byte[] $Expected.Length
$n = $fs.Read($buf, 0, $buf.Length)
} finally { $fs.Close() }
if ($n -ne $Expected.Length) { return $false }
for ($i = 0; $i -lt $Expected.Length; $i++) { if ($buf[$i] -ne $Expected[$i]) { return $false } }
return $true
}
$jumpChecks = @(
@{ File = 'vtoyjump64.exe'; Offset = 0x810E; Bytes = [byte[]](0xB3, 0x01, 0x90); Name = 'mov $1,%bl; nop' },
@{ File = 'vtoyjump32.exe'; Offset = 0x6FEB; Bytes = [byte[]](0x90, 0x90); Name = 'nop nop' },
@{ File = 'vtoyjump32.exe'; Offset = 0x6FF3; Bytes = [byte[]](0x90, 0x90, 0x90, 0x90, 0x90, 0x90); Name = 'nop x6' }
)
foreach ($c in $jumpChecks) {
$path = Join-Path "${DriveLetter}:\ventoy" $c.File
if (Test-ByteAt $path $c.Offset $c.Bytes) {
Write-Ok ("{0} @0x{1:X}: патч на месте ({2})" -f $c.File, $c.Offset, $c.Name)
} else {
Write-Warn ("{0} @0x{1:X}: патч MBR check НЕ применён — ISO в PE не смонтируется!" -f $c.File, $c.Offset)
}
}
Write-Step "Готово"
Get-Item "${DriveLetter}:\grub\grub.cfg", "${DriveLetter}:\grub\fonts\unicode.pf2", "${DriveLetter}:\ventoy\core.img", "${DriveLetter}:\EFI\BOOT\BOOTX64.EFI" |
Select-Object FullName, Length | Format-Table -AutoSize
Write-Host "Теперь можно загружать Xorboot -> Ventoy (1.1.18, MBR check отключён в core и в vtoyjump)." -ForegroundColor Green