Files
Ventoy/build-scripts/layout/insert-ventoy-p2.ps1
T

375 lines
18 KiB
PowerShell
Raw 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
Вставляет 32-МБ раздел VTOYEFI между p1 (FAT32, проект) и p2 (NTFS, ESD),
переставляя записи разделов в MBR: ESD становится p3.
.DESCRIPTION
Исходная схема (как в вашем README):
p1 FAT32 >=15 GB проект PF + ISO
p2 NTFS >=15 GB Windows ESD
Целевая схема:
p1 FAT32 проект (уменьшен на 32 МБ + 1 МБ запас)
p2 FAT 32 МБ VTOYEFI + /ventoy/core.img
p3 NTFS ESD тот же offset и размер, что были у p2
Данные ESD не перемещаются: меняется только номер записи в таблице MBR.
MBR-код (xorboot/grub4dos) не перезаписывается.
Скрипт делает резервные копии сектора 0 в папку backup.
.PARAMETER DiskNumber
Номер физического диска из Get-Disk.
.PARAMETER SourceDir
Папка с vtoyefi, core.img, grldr-ventoy.
.PARAMETER AllowNonUsb
Разрешить не-USB диск (только для тестов).
.EXAMPLE
.\insert-ventoy-p2.ps1 -DiskNumber 2 -WhatIf
.EXAMPLE
.\insert-ventoy-p2.ps1 -DiskNumber 2
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true)]
[int]$DiskNumber,
[string]$SourceDir = $PSScriptRoot,
[switch]$AllowNonUsb
)
$ErrorActionPreference = 'Stop'
$MiB = 1MB
$VentoySize = 32MB # 65536 * 512
$P1Offset = 1MB # LBA 2048
$Margin = 1MB # запас, чтобы p2 гарантированно не залез на ESD
$Label = 'VTOYEFI'
$BackupDir = Join-Path $SourceDir 'backup'
$SectorSize = 512
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 }
# ---------------------------------------------------------------------------
# Работа с сектором 0 через физический диск
# ---------------------------------------------------------------------------
function Read-DiskSector {
param([int]$Disk, [uint64]$Lba, [int]$Count = 1)
$path = "\\.\PhysicalDrive$Disk"
$fs = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite)
try {
$fs.Seek([int64]($Lba * $SectorSize), [IO.SeekOrigin]::Begin) | Out-Null
$buf = New-Object byte[] ($Count * $SectorSize)
$read = 0
while ($read -lt $buf.Length) {
$n = $fs.Read($buf, $read, $buf.Length - $read)
if ($n -le 0) { throw "Короткое чтение сектора $Lba" }
$read += $n
}
return ,$buf
} finally {
$fs.Dispose()
}
}
function Write-DiskSector {
param([int]$Disk, [uint64]$Lba, [byte[]]$Data)
if ($Data.Length % $SectorSize -ne 0) { throw "Размер данных не кратен 512." }
$path = "\\.\PhysicalDrive$Disk"
$fs = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite)
try {
$fs.Seek([int64]($Lba * $SectorSize), [IO.SeekOrigin]::Begin) | Out-Null
$fs.Write($Data, 0, $Data.Length)
$fs.Flush()
} finally {
$fs.Dispose()
}
}
function Get-MbrEntry {
param([byte[]]$Mbr, [int]$Index)
$o = 446 + 16 * $Index
[pscustomobject]@{
Index = $Index
Status = $Mbr[$o]
Type = $Mbr[$o + 4]
StartLba = [BitConverter]::ToUInt32($Mbr, $o + 8)
Sectors = [BitConverter]::ToUInt32($Mbr, $o + 12)
}
}
function Test-FatType([byte]$Type) {
return ($Type -in @(0x01, 0x04, 0x06, 0x0B, 0x0C, 0x0E, 0xEF))
}
# ---------------------------------------------------------------------------
Write-Step "Проверка исходных файлов"
$vtoyefi = Join-Path $SourceDir 'vtoyefi'
$coreImg = Join-Path $SourceDir 'ventoy-1.1.18\boot\core.img'
if (-not (Test-Path $coreImg)) { $coreImg = Join-Path $SourceDir 'core.img' }
$grldr = Join-Path $SourceDir 'grldr-ventoy'
foreach ($p in @($vtoyefi, $coreImg)) {
if (-not (Test-Path $p)) { throw "Не найден обязательный элемент: $p" }
}
if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) {
throw "В $vtoyefi нет ventoy\ventoy.cpio — это не распакованный VTOYEFI."
}
Write-Ok "VTOYEFI: $vtoyefi"
Write-Ok "core.img: $coreImg"
# ---------------------------------------------------------------------------
Write-Step "Проверка диска $DiskNumber"
$disk = Get-Disk -Number $DiskNumber -ErrorAction Stop
if ($disk.IsBoot -or $disk.IsSystem) { throw "Диск $DiskNumber загрузочный/системный. Отказ." }
if (-not $AllowNonUsb -and $disk.BusType -notin @('USB', 'SD', 'MMC')) {
throw "Диск $DiskNumber имеет BusType '$($disk.BusType)', а не USB/SD. Отказ (тест: -AllowNonUsb)."
}
if ($disk.PartitionStyle -ne 'MBR') {
throw "Нужна MBR-разметка. Сейчас: $($disk.PartitionStyle)."
}
$parts = @(Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset)
if ($parts.Count -ne 2) {
$desc = ($parts | ForEach-Object { "p$($_.PartitionNumber) offset=$($_.Offset) size=$($_.Size)" }) -join '; '
throw "Ожидались ровно 2 раздела (проект + ESD). Сейчас: $desc"
}
$p1 = $parts | Where-Object { $_.PartitionNumber -eq 1 }
$esd = $parts | Where-Object { $_.PartitionNumber -eq 2 }
if (-not $p1 -or -not $esd) { throw "Не найдены p1 и p2." }
if ($p1.Offset -ne $P1Offset) {
Write-Warn ("p1 начинается с offset {0} (LBA {1}), Ventoy ожидает 2048." -f $p1.Offset, ($p1.Offset / 512))
Write-Warn "Загрузка возможна, но с предупреждением 'NOT a standard Ventoy device'."
}
if ($esd.Offset -lt ($p1.Offset + $p1.Size)) { throw "p2 пересекается с p1." }
$vol1 = Get-Volume -Partition $p1 -ErrorAction Stop
if (-not $vol1.DriveLetter) { throw "У p1 нет буквы диска." }
$volEsd = Get-Volume -Partition $esd -ErrorAction Stop
if (-not $volEsd.DriveLetter) { Write-Warn "У ESD-раздела нет буквы диска; это не мешает операции." }
$p1End = $p1.Offset + $p1.Size
$gap = $esd.Offset - $p1End
if ($gap -lt 0) { throw "Отрицательный зазор между p1 и p2." }
# Сколько нужно освободить в p1, чтобы перед ESD влезли 32 МБ + запас
$need = [Math]::Max(0, $VentoySize - $gap)
$shrink = if ($need -gt 0) { $need + $Margin } else { 0 }
$newP1Size = $p1.Size - $shrink
if ($newP1Size -le 0) { throw "p1 слишком мал." }
if ($shrink -gt 0 -and $vol1.SizeRemaining -lt $shrink) {
throw ("На p1 свободно {0:N1} MB, а освободить нужно {1:N1} MB." -f ($vol1.SizeRemaining / 1MB), ($shrink / 1MB))
}
Write-Host ("Диск: {0}, {1:N1} GB, MBR, BusType={2}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.BusType)
Write-Host ("p1 : offset={0} (LBA {1}), size={2:N1} MB, {3}" -f $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1MB), $vol1.DriveLetter)
Write-Host ("p2 : offset={0} (LBA {1}), size={2:N1} MB, ESD" -f $esd.Offset, ($esd.Offset / 512), ($esd.Size / 1MB))
Write-Host ("Зазор между p1 и p2: {0:N1} MB" -f ($gap / 1MB))
if ($shrink -gt 0) {
Write-Host ("План: уменьшить p1 на {0:N1} MB (с {1:N1} до {2:N1} MB), начало p1 не меняется." -f ($shrink / 1MB), ($p1.Size / 1MB), ($newP1Size / 1MB))
} else {
Write-Host "План: свободного места уже достаточно, p1 не трогаем."
}
Write-Host "План: создать p3 = 32 МБ FAT (VTOYEFI) в зазоре, затем поменять местами записи MBR p2 и p3."
Write-Host "План: ESD останется на том же offset/размере, но станет p3. Данные ESD не перемещаются."
if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "Вставить 32-МБ VTOYEFI между p1 и ESD и переставить записи MBR p2/p3")) {
Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow
return
}
# ---------------------------------------------------------------------------
Write-Step "Резервная копия MBR"
New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$mbrBefore = Read-DiskSector -Disk $DiskNumber -Lba 0
$mbrBeforePath = Join-Path $BackupDir "mbr-before-$stamp.bin"
[IO.File]::WriteAllBytes($mbrBeforePath, $mbrBefore)
Write-Ok "MBR сохранён: $mbrBeforePath"
$ventoyCreated = $false
$mbrSwapped = $false
try {
# -----------------------------------------------------------------------
if ($shrink -gt 0) {
Write-Step "Уменьшение p1 на $([Math]::Round($shrink / 1MB, 1)) MB"
Write-Warn "Windows может отказать, если данные p1 лежат в самом конце раздела. Сделайте бэкап."
Resize-Partition -DriveLetter $vol1.DriveLetter -Size $newP1Size -ErrorAction Stop
Start-Sleep -Seconds 2
}
$p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1
$p2Offset = $p1After.Offset + $p1After.Size
$p2End = $p2Offset + $VentoySize
# Если Windows округлил размер p1 вверх и p2 залезает на ESD — добираем
if ($p2End -gt $esd.Offset) {
$excess = $p2End - $esd.Offset
Write-Warn ("p2 залезает на ESD на {0} байт; уменьшаю p1 ещё." -f $excess)
$target = $p1After.Size - $excess - $Margin
Resize-Partition -DriveLetter $vol1.DriveLetter -Size $target -ErrorAction Stop
Start-Sleep -Seconds 2
$p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1
$p2Offset = $p1After.Offset + $p1After.Size
$p2End = $p2Offset + $VentoySize
}
if ($p2End -gt $esd.Offset) { throw "Не удалось освободить 32 МБ перед ESD." }
Write-Ok ("p1: новый конец {0} (LBA {1})" -f ($p1After.Size + $p1After.Offset), (($p1After.Size + $p1After.Offset) / 512))
Write-Ok ("Будущий p2: offset={0} (LBA {1}), конец={2} (LBA {3})" -f $p2Offset, ($p2Offset / 512), $p2End, ($p2End / 512))
# -----------------------------------------------------------------------
Write-Step "Создание раздела 32 МБ в зазоре"
try {
$ventoy = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 512 -AssignDriveLetter -ErrorAction Stop
} catch {
Write-Warn "Не удалось создать с Alignment=512: $($_.Exception.Message)"
throw
}
$ventoyCreated = $true
if ($ventoy.PartitionNumber -ne 3) { throw "Ожидался номер раздела 3, получен $($ventoy.PartitionNumber)." }
if ($ventoy.Offset -ne $p2Offset) { throw "Windows сдвинул начало p3: $($ventoy.Offset) != $p2Offset." }
if ($ventoy.Size -ne $VentoySize) { throw "Размер p3 $($ventoy.Size) != $VentoySize." }
Write-Ok "p3 создан: offset=$($ventoy.Offset), size=$($ventoy.Size)"
Start-Sleep -Seconds 1
$ventoyVol = Get-Volume -Partition $ventoy -ErrorAction Stop
if (-not $ventoyVol.DriveLetter) { throw "У нового раздела нет буквы диска." }
Write-Step "Форматирование p3 в FAT"
Format-Volume -DriveLetter $ventoyVol.DriveLetter -FileSystem FAT -NewFileSystemLabel $Label -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
Write-Step "Копирование VTOYEFI и core.img"
$p3Root = "$($ventoyVol.DriveLetter):\"
Copy-Item -Path (Join-Path $vtoyefi '*') -Destination $p3Root -Recurse -Force -ErrorAction Stop
if (-not (Test-Path (Join-Path $p3Root 'ventoy\ventoy.cpio'))) { throw "Не найден $p3Root\ventoy\ventoy.cpio" }
Copy-Item -Path $coreImg -Destination (Join-Path $p3Root 'ventoy\core.img') -Force -ErrorAction Stop
Write-Ok "VTOYEFI и core.img скопированы."
# -----------------------------------------------------------------------
Write-Step "Перестановка записей MBR p2 <-> p3"
$mbrPre = Read-DiskSector -Disk $DiskNumber -Lba 0
$mbrPrePath = Join-Path $BackupDir "mbr-pre-swap-$stamp.bin"
[IO.File]::WriteAllBytes($mbrPrePath, $mbrPre)
Write-Ok "MBR до перестановки: $mbrPrePath"
$e1 = Get-MbrEntry $mbrPre 0
$e2 = Get-MbrEntry $mbrPre 1
$e3 = Get-MbrEntry $mbrPre 2
if ($e1.StartLba -ne 2048) { Write-Warn "p1 start LBA = $($e1.StartLba), не 2048." }
if ($e2.StartLba -ne [uint32]($esd.Offset / 512) -or $e2.Sectors -ne [uint32]($esd.Size / 512)) {
throw "Запись p2 в MBR не совпадает с ESD (start=$($e2.StartLba), sectors=$($e2.Sectors))."
}
if ($e2.Type -eq 0x05 -or $e2.Type -eq 0x0F) { throw "ESD — расширенный/логический раздел; эта схема не поддерживается." }
if ($e3.StartLba -ne [uint32]($p2Offset / 512) -or $e3.Sectors -ne [uint32](65536)) {
throw "Запись p3 в MBR не совпадает с новым разделом (start=$($e3.StartLba), sectors=$($e3.Sectors))."
}
if (-not (Test-FatType $e3.Type)) { throw ("Тип p3 0x{0:X2} не похож на FAT." -f $e3.Type) }
$mbrNew = [byte[]]$mbrPre.Clone()
for ($i = 0; $i -lt 16; $i++) {
$t = $mbrNew[462 + $i]
$mbrNew[462 + $i] = $mbrNew[478 + $i]
$mbrNew[478 + $i] = $t
}
# Если p1 активен, не даём флагу активности уехать на Ventoy/ESD
if ($mbrNew[446] -eq 0x80) {
$mbrNew[462] = 0x00
$mbrNew[478] = 0x00
}
Write-DiskSector -Disk $DiskNumber -Lba 0 -Data $mbrNew
$mbrSwapped = $true
Start-Sleep -Seconds 1
# -----------------------------------------------------------------------
Write-Step "Проверка MBR после перестановки"
$mbrCheck = Read-DiskSector -Disk $DiskNumber -Lba 0
$c1 = Get-MbrEntry $mbrCheck 0
$c2 = Get-MbrEntry $mbrCheck 1
$c3 = Get-MbrEntry $mbrCheck 2
$ok = $true
if ($c2.StartLba -ne [uint32]($p2Offset / 512) -or $c2.Sectors -ne [uint32]65536) { $ok = $false }
if ($c3.StartLba -ne [uint32]($esd.Offset / 512) -or $c3.Sectors -ne [uint32]($esd.Size / 512)) { $ok = $false }
if ($c1.StartLba -ne $e1.StartLba -or $c1.Sectors -ne $e1.Sectors) { $ok = $false }
if (-not $ok) {
Write-DiskSector -Disk $DiskNumber -Lba 0 -Data $mbrPre
throw "Проверка MBR не прошла; восстановлен MBR до перестановки ($mbrPrePath)."
}
Write-Ok "p2 = Ventoy (32 МБ), p3 = ESD (offset не изменился)."
# Обновляем кэш Windows (может не сработать без переподключения)
try { Update-HostStorageCache -ErrorAction SilentlyContinue } catch { }
Start-Sleep -Seconds 1
# -----------------------------------------------------------------------
Write-Step "Артефакты в папке проекта на p1"
$projFolder = Join-Path "$($vol1.DriveLetter):\" 'efi\Paravis\Ventoy'
New-Item -ItemType Directory -Path $projFolder -Force | Out-Null
Copy-Item -Path $coreImg -Destination (Join-Path $projFolder 'core.img') -Force
if (Test-Path $grldr) {
Copy-Item -Path $grldr -Destination (Join-Path $projFolder 'grldr-ventoy') -Force
$g4d = Join-Path "$($vol1.DriveLetter):\" 'efi\Paravis\Boot\g4d'
if (Test-Path $g4d) {
Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force
Write-Ok "grldr-ventoy -> $g4d\Ventoy"
}
}
Write-Ok "core.img и grldr-ventoy -> $projFolder"
# -----------------------------------------------------------------------
Write-Step "Готово. Что делать дальше"
Write-Host @"
Разметка теперь:
p1 FAT32 проект + ISO (как раньше, уменьшен на 32-33 МБ)
p2 FAT 32 МБ VTOYEFI (новый)
p3 NTFS ESD (тот же offset/размер, буква диска обычно сохраняется)
BIOS / grub4dos:
title Ventoy 1.1.18 (BIOS)
find --set-root /ventoy/core.img
kernel /ventoy/core.img
boot
UEFI / Xorboot:
раздел p2 (VTOYEFI), файл \EFI\BOOT\BOOTX64.EFI
Важно:
* ESD-раздел теперь p3. Если где-то был захардкожен номер "2" — поправьте на "3".
Буква диска и данные не менялись.
* После изменения таблицы разделов желательно переподключить флешку,
чтобы Windows перечитала MBR.
* Change_bootLoader.exe при необходимости запустите заново: p1 остался p1.
Резервные копии MBR:
$mbrBeforePath
$mbrPrePath
Откат (если передумаете):
1) удалить p2 (Ventoy, 32 МБ) в diskpart — это НЕ ESD;
2) расширить p1 обратно на 32-33 МБ;
3) восстановить $mbrBeforePath в сектор 0 (ESD снова станет p2).
"@ -ForegroundColor Gray
}
catch {
Write-Host ""
Write-Warn "Ошибка: $($_.Exception.Message)"
Write-Host "Состояние: p1 мог быть уменьшен; новый раздел мог быть создан." -ForegroundColor Yellow
Write-Host "Резервные копии MBR: $BackupDir" -ForegroundColor Yellow
if ($mbrSwapped) {
Write-Host "MBR уже переставлялся — проверьте разделы перед продолжением." -ForegroundColor Yellow
}
throw
}