Add build, deploy and test sources

This commit is contained in:
Paravis committed 2026-11-13 07:52:37 +03:00
1 parent b962581812
commit 3d1a08f230
259 files changed
+15273

No files matched your search

@@ -0,0 +1,268 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Вариант B: один большой p1 для данных + p2 Ventoy + p3 14 ГБ для загрузки.
Диск полностью очищается.
.DESCRIPTION
Создаёт:
p1 ~462 ГБ NTFS ESD + ISO + личные файлы (данные Ventoy)
p2 32 МБ FAT VTOYEFI + core.img
p3 14 ГБ FAT32 проект PF + Xorboot (активный раздел)
Почему так:
* Ventoy требует p1 = данные, p2 = VTOYEFI сразу после p1;
* p3 FAT32 нужен для UEFI (прошивка не читает NTFS/exFAT);
* ESD install_10_x64.esd (4.26 ГиБ) и install_11.esd (4.44 ГиБ)
не влезают в FAT32, поэтому данные — на NTFS p1.
Change_bootLoader.exe использует букву диска, с которого запущен,
поэтому его можно запускать с p3 — PBR ставится на p3, MBR на диск.
p3 помечается активным.
.PARAMETER DiskNumber
Номер физического диска из Get-Disk.
.PARAMETER BootSizeGB
Размер p3 (проект + загрузчик) в ГБ. По умолчанию 14.
.PARAMETER DataFs
Файловая система p1: NTFS (по умолчанию) или exFAT.
.PARAMETER ProjectDir
Папка PF (C:\PF\PF).
.PARAMETER SkipProject
Не копировать PF на p3.
.PARAMETER AllowNonUsb
Для USB-переходников, которые Windows показывает не как USB.
.PARAMETER Force
Не спрашивать YES.
.EXAMPLE
.\create-ventoy-bigp1.ps1 -DiskNumber 2 -WhatIf
.EXAMPLE
.\create-ventoy-bigp1.ps1 -DiskNumber 2 -BootSizeGB 14
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true)]
[int]$DiskNumber,
[int]$BootSizeGB = 14,
[int]$TailReserveMB = 50,
[ValidateSet('NTFS', 'exFAT')]
[string]$DataFs = 'NTFS',
[string]$ProjectDir = 'C:\PF\PF',
[string]$SourceDir = $PSScriptRoot,
[switch]$SkipProject,
[switch]$AllowNonUsb,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
$MiB = 1MB
$VentoySize = 32MB
$P1Offset = 1MB
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 }
# ---------------------------------------------------------------------------
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'
if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Не найден распакованный VTOYEFI: $vtoyefi" }
if (-not (Test-Path $coreImg)) { throw "Не найден core.img: $coreImg" }
if (-not $SkipProject -and -not (Test-Path $ProjectDir)) { throw "Не найдена папка проекта: $ProjectDir" }
Write-Ok "VTOYEFI: $vtoyefi"
Write-Ok "core.img: $coreImg"
# ---------------------------------------------------------------------------
Write-Step "Проверка диска $DiskNumber"
if ($BootSizeGB -lt 14) { throw "BootSizeGB должен быть >= 14 (проект PF занимает 13.26 ГиБ)." }
$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)."
}
$bootSize = [uint64]$BootSizeGB * 1GB
$tailReserve = [uint64]$TailReserveMB * 1MB
# Считаем с конца: p3 фиксирован, p2 перед ним, p1 — всё остальное.
# Оставляем 50 МБ неразмеченного хвоста: некоторые USB-мостики
# (Realtek RTL9210B и др.) отдают в конце лишние МБ, которые Windows
# не даёт занять, и раздел «впритык» падает с Not enough capacity.
$p3Offset = [Math]::Floor(($disk.Size - $tailReserve - $bootSize) / 1MB) * 1MB
$p2Offset = $p3Offset - $VentoySize
$p1Size = $p2Offset - $P1Offset
$p3Size = $bootSize
if ($p1Size -lt 1GB) { throw "Диск слишком мал: p1 получается меньше 1 ГБ." }
if ($p2Offset -le $P1Offset) { throw "Диск слишком мал для p2/p3." }
if (($p3Offset + $p3Size + $tailReserve) -gt $disk.Size) { throw "Внутренняя ошибка: p3 + хвост выходят за диск." }
if (-not $SkipProject) {
$projBytes = [uint64]((Get-ChildItem -Path $ProjectDir -Recurse -File -ErrorAction Stop | Measure-Object Length -Sum).Sum)
$freeBytes = $bootSize - $projBytes
Write-Host ("PF: {0:N2} ГиБ; p3: {1:N2} ГиБ; останется: {2:N2} ГиБ" -f ($projBytes / 1GB), ($bootSize / 1GB), ($freeBytes / 1GB))
if ($freeBytes -lt 256MB) { throw ("PF занимает {0:N2} ГиБ, p3 = {1} ГиБ. Увеличьте -BootSizeGB (16/18)." -f ($projBytes / 1GB), $BootSizeGB) }
if ($freeBytes -lt 1GB) { Write-Warn "На p3 меньше 1 ГиБ свободно; при ошибке robocopy увеличьте -BootSizeGB." }
}
Write-Host ("Диск: {0}, {1:N1} ГиБ, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.PartitionStyle, $disk.BusType)
Write-Host ("p1: {0:N1} ГиБ {1} — данные (ESD/ISO/личные), LBA 2048" -f ($p1Size / 1GB), $DataFs)
Write-Host ("p2: 32 МБ FAT — Ventoy, offset {0} (LBA {1})" -f $p2Offset, ($p2Offset / 512))
Write-Host ("p3: {0:N1} ГиБ FAT32 — проект PF + Xorboot, активный, offset {1} (LBA {2})" -f ($p3Size / 1GB), $p3Offset, ($p3Offset / 512))
Write-Host ("Хвост-резерв: {0:N1} МБ (неразмеченный, чтобы Windows не ругался на конец диска)" -f ($tailReserve / 1MB))
Write-Host "План: диск будет полностью очищен."
if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "ПОЛНОСТЬЮ ОЧИСТИТЬ: p1 данные + p2 Ventoy + p3 проект/загрузчик")) {
Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow
return
}
if (-not $Force) {
$ans = Read-Host "Введите YES для полной очистки диска $DiskNumber ($($disk.FriendlyName))"
if ($ans -ne 'YES') { throw "Отменено пользователем." }
}
# ---------------------------------------------------------------------------
Write-Step "Очистка и MBR"
Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false -ErrorAction Stop
Initialize-Disk -Number $DiskNumber -PartitionStyle MBR -ErrorAction Stop
Start-Sleep -Seconds 2
Write-Ok "Диск очищен, MBR создан."
# ---------------------------------------------------------------------------
Write-Step "p1: данные ($DataFs)"
$p1 = New-Partition -DiskNumber $DiskNumber -Offset $P1Offset -Size $p1Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v1 = Get-Volume -Partition $p1 -ErrorAction Stop
Format-Volume -DriveLetter $v1.DriveLetter -FileSystem $DataFs -NewFileSystemLabel 'DATA' -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v1 = Get-Volume -Partition $p1 -ErrorAction Stop
Write-Ok ("p1: {0}: offset={1} (LBA {2}), size={3:N1} ГиБ, {4}" -f $v1.DriveLetter, $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1GB), $DataFs)
# ---------------------------------------------------------------------------
Write-Step "p2: VTOYEFI 32 МБ"
$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v2 = Get-Volume -Partition $p2 -ErrorAction Stop
Format-Volume -DriveLetter $v2.DriveLetter -FileSystem FAT -NewFileSystemLabel 'VTOYEFI' -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v2 = Get-Volume -Partition $p2 -ErrorAction Stop
Write-Ok ("p2: {0}: offset={1} (LBA {2}), size={3:N1} МБ" -f $v2.DriveLetter, $p2.Offset, ($p2.Offset / 512), ($p2.Size / 1MB))
# ---------------------------------------------------------------------------
Write-Step "p3: проект PF + загрузчик (FAT32, 14 ГБ)"
$p3 = New-Partition -DiskNumber $DiskNumber -Offset $p3Offset -Size $p3Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v3 = Get-Volume -Partition $p3 -ErrorAction Stop
Format-Volume -DriveLetter $v3.DriveLetter -FileSystem FAT32 -NewFileSystemLabel 'PARAVIS' -AllocationUnitSize 4096 -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v3 = Get-Volume -Partition $p3 -ErrorAction Stop
Write-Ok ("p3: {0}: offset={1} (LBA {2}), size={3:N1} ГиБ, FAT32" -f $v3.DriveLetter, $p3.Offset, ($p3.Offset / 512), ($p3.Size / 1GB))
# ---------------------------------------------------------------------------
Write-Step "Копирование проекта PF на p3"
if ($SkipProject) {
Write-Warn "Пропущено (-SkipProject)."
} else {
# Важно: не использовать Start-Process с "H:\" — обратный слэш перед
# закрывающей кавычкой ломает командную строку. Вызов через & и массив
# аргументов передаёт путь корректно.
$roboArgs = @(
$ProjectDir,
"$($v3.DriveLetter):\",
'/E', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS'
)
& robocopy.exe @roboArgs
$rc = $LASTEXITCODE
if ($rc -ge 8) {
throw ("robocopy завершился с кодом {0}. Код 8 — не все файлы (место/доступ), 16 — серьёзная ошибка. Если мало места — увеличьте -BootSizeGB (16/18)." -f $rc)
}
Write-Ok "Проект скопирован на $($v3.DriveLetter):"
}
# ---------------------------------------------------------------------------
Write-Step "VTOYEFI на p2"
Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "$($v2.DriveLetter):\" -Recurse -Force -ErrorAction Stop
if (-not (Test-Path "$($v2.DriveLetter):\ventoy\ventoy.cpio")) { throw "VTOYEFI скопирован не полностью." }
Copy-Item -Path $coreImg -Destination "$($v2.DriveLetter):\ventoy\core.img" -Force -ErrorAction Stop
Write-Ok "VTOYEFI + core.img -> $($v2.DriveLetter):"
# ---------------------------------------------------------------------------
Write-Step "Артефакты на p3"
$projFolder = "$($v3.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 = "$($v3.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 "Подготовка p1 для данных"
New-Item -ItemType Directory -Path "$($v1.DriveLetter):\ISO" -Force | Out-Null
New-Item -ItemType Directory -Path "$($v1.DriveLetter):\WindowsESD" -Force | Out-Null
Write-Ok "Созданы $($v1.DriveLetter):\ISO и $($v1.DriveLetter):\WindowsESD"
# ---------------------------------------------------------------------------
Write-Step "Активный раздел p3"
Set-Partition -DiskNumber $DiskNumber -PartitionNumber 3 -IsActive $true -ErrorAction Stop
Write-Ok "p3 помечен активным (с него грузится Xorboot/grub4dos/bootmgr)."
# ---------------------------------------------------------------------------
Write-Step "Проверка"
Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type -AutoSize
$c3 = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 3
if (-not $c3.IsActive) { Write-Warn "p3 не активен — проверьте." }
Write-Step "Готово. Что делать дальше"
$msg = @"
Разметка:
p1 {0}: {1} данные: ISO + WindowsESD + личные файлы
p2 {2}: FAT 32 МБ VTOYEFI
p3 {3}: FAT32 14 ГБ проект PF, активный
Далее:
1) Запустите {3}:\Change_bootLoader.exe (можно из любой папки на p3)
и выберите Legacy + UEFI. Он возьмёт букву {3}:, поставит PBR на p3,
MBR — на диск.
2) BIOS: Xorboot/grub4dos будет искать \efi\Paravis\Boot\... на p3.
Для Ventoy добавьте пункт на \efi\Paravis\Boot\g4d\Ventoy
(или find --set-root /ventoy/core.img; kernel /ventoy/core.img).
3) UEFI: прошивка увидит FAT32 p3 и загрузит \efi\Boot\bootx64.efi (Xorboot).
В Xorboot добавьте Ventoy: p2 {2}: \EFI\BOOT\BOOTX64.EFI.
4) Распакуйте 3_PF_WindowsESD.zip в {0}:\WindowsESD (NTFS, >4 ГиБ влезают).
5) ISO кладите в {0}:\ISO — Ventoy сканирует p1 и увидит их без Vlnk.
Важно: Ventoy стоит p2 сразу после p1, а p3 — после Ventoy, поэтому
Ventoy не последний раздел. Строго последним он быть не может, если
после него есть загрузочный p3.
"@ -f $v1.DriveLetter, $DataFs, $v2.DriveLetter, $v3.DriveLetter
Write-Host $msg -ForegroundColor Gray
Write-Ok "Готово."
+241
View File
@@ -0,0 +1,241 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Полная разметка USB-диска под проект Paravis + Ventoy + ESD.
ВНИМАНИЕ: диск полностью очищается.
.DESCRIPTION
Создаёт:
p1 FAT32 проект PF + ISO (по умолчанию 20 ГБ)
p2 FAT 32 МБ VTOYEFI + core.img
p3 NTFS остаток диска под ESD
p1 начинается с LBA 2048 (1 МБ), p2 — сразу после p1, p3 — сразу после p2.
Это штатная схема Ventoy: data=p1, VTOYEFI=p2.
MBR-код затем ставится вашим Change_bootLoader.exe (скрипт его не запускает).
.PARAMETER DiskNumber
Номер физического диска из Get-Disk (только USB, не системный).
.PARAMETER P1SizeGB
Размер p1 в ГБ. По умолчанию 20. Для FAT32 Windows практический максимум 32.
.PARAMETER ProjectDir
Папка с проектом PF (по умолчанию C:\PF\PF).
.PARAMETER SkipProject
Не копировать проект PF на p1.
.PARAMETER Force
Не спрашивать YES (для автоматизации). Всё равно проверяет, что диск USB.
.EXAMPLE
.\create-ventoy-usb.ps1 -DiskNumber 2 -WhatIf
.EXAMPLE
.\create-ventoy-usb.ps1 -DiskNumber 2 -P1SizeGB 32
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true)]
[int]$DiskNumber,
[int]$P1SizeGB = 14,
[string]$ProjectDir = 'C:\PF\PF',
[string]$SourceDir = $PSScriptRoot,
[switch]$SkipProject,
[switch]$AllowNonUsb,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
$MiB = 1MB
$VentoySize = 32MB
$P1Offset = 1MB
$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 }
# ---------------------------------------------------------------------------
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'
if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) {
throw "Не найден распакованный VTOYEFI: $vtoyefi"
}
if (-not (Test-Path $coreImg)) { throw "Не найден core.img: $coreImg" }
if (-not $SkipProject -and -not (Test-Path $ProjectDir)) {
throw "Не найдена папка проекта: $ProjectDir (или используйте -SkipProject)."
}
Write-Ok "VTOYEFI: $vtoyefi"
Write-Ok "core.img: $coreImg"
# ---------------------------------------------------------------------------
Write-Step "Проверка диска $DiskNumber"
if ($P1SizeGB -lt 15) { throw "P1SizeGB должен быть >= 15." }
if ($P1SizeGB -gt 32) { Write-Warn "FAT32 больше 32 ГБ Windows может не отформатировать." }
$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. Отказ (для USB-переходников: -AllowNonUsb)."
}
$p1Size = [uint64]$P1SizeGB * 1GB
$need = $P1Offset + $p1Size + $VentoySize + 1GB
if ($disk.Size -lt $need) {
throw ("Диск слишком мал: {0:N1} GB, нужно минимум {1:N1} GB." -f ($disk.Size / 1GB), ($need / 1GB))
}
# Проверяем, что проект PF влезает в p1, ДО очистки диска
if (-not $SkipProject) {
$projBytes = [uint64]((Get-ChildItem -Path $ProjectDir -Recurse -File -ErrorAction Stop | Measure-Object Length -Sum).Sum)
$freeBytes = $p1Size - $projBytes
Write-Host ("PF: {0:N2} GiB; p1: {1:N2} GiB; останется: {2:N2} GiB" -f ($projBytes / 1GB), ($p1Size / 1GB), ($freeBytes / 1GB))
if ($freeBytes -lt 256MB) {
throw ("Проект PF занимает {0:N2} GiB, а p1 = {1} ГиБ. Увеличьте -P1SizeGB (например, 16 или 20)." -f ($projBytes / 1GB), $P1SizeGB)
}
if ($freeBytes -lt 1GB) {
Write-Warn "На p1 останется меньше 1 ГиБ. FAT32 может не принять проект из-за кластеров; при ошибке robocopy увеличьте -P1SizeGB до 16-20."
}
}
Write-Host ("Диск: {0}, {1:N1} GB, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.PartitionStyle, $disk.BusType)
Write-Host ("План: p1 FAT32 {0} ГБ с LBA 2048; p2 FAT 32 МБ сразу после p1; p3 NTFS — остаток ({1:N1} ГБ)." -f $P1SizeGB, (($disk.Size - $P1Offset - $p1Size - $VentoySize) / 1GB))
Write-Host "План: диск будет полностью очищен. MBR-код поставите Change_bootLoader.exe после копирования."
if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "ПОЛНОСТЬЮ ОЧИСТИТЬ и создать p1 FAT32 + p2 32MB VTOYEFI + p3 NTFS")) {
Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow
return
}
if (-not $Force) {
$ans = Read-Host "Введите YES для полной очистки диска $DiskNumber ($($disk.FriendlyName))"
if ($ans -ne 'YES') { throw "Отменено пользователем." }
}
# ---------------------------------------------------------------------------
Write-Step "Очистка и инициализация MBR"
Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false -ErrorAction Stop
Initialize-Disk -Number $DiskNumber -PartitionStyle MBR -ErrorAction Stop
Start-Sleep -Seconds 2
Write-Ok "Диск очищен, MBR создан."
# ---------------------------------------------------------------------------
Write-Step "Создание p1 (FAT32, проект)"
$p1 = New-Partition -DiskNumber $DiskNumber -Offset $P1Offset -Size $p1Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v1 = Get-Volume -Partition $p1 -ErrorAction Stop
Format-Volume -DriveLetter $v1.DriveLetter -FileSystem FAT32 -NewFileSystemLabel 'PARAVIS' -AllocationUnitSize 4096 -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v1 = Get-Volume -Partition $p1 -ErrorAction Stop
Write-Ok ("p1: {0}: offset={1} (LBA {2}), size={3:N1} GB" -f $v1.DriveLetter, $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1GB))
# ---------------------------------------------------------------------------
Write-Step "Создание p2 (VTOYEFI, 32 МБ)"
$p2Offset = $p1.Offset + $p1.Size
$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v2 = Get-Volume -Partition $p2 -ErrorAction Stop
Format-Volume -DriveLetter $v2.DriveLetter -FileSystem FAT -NewFileSystemLabel 'VTOYEFI' -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v2 = Get-Volume -Partition $p2 -ErrorAction Stop
Write-Ok ("p2: {0}: offset={1} (LBA {2}), size={3:N1} MB" -f $v2.DriveLetter, $p2.Offset, ($p2.Offset / 512), ($p2.Size / 1MB))
# ---------------------------------------------------------------------------
Write-Step "Создание p3 (NTFS, ESD)"
$p3Offset = $p2.Offset + $p2.Size
$p3 = New-Partition -DiskNumber $DiskNumber -Offset $p3Offset -UseMaximumSize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$v3 = Get-Volume -Partition $p3 -ErrorAction Stop
Format-Volume -DriveLetter $v3.DriveLetter -FileSystem NTFS -NewFileSystemLabel 'ESD' -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
$v3 = Get-Volume -Partition $p3 -ErrorAction Stop
Write-Ok ("p3: {0}: offset={1} (LBA {2}), size={3:N1} GB" -f $v3.DriveLetter, $p3.Offset, ($p3.Offset / 512), ($p3.Size / 1GB))
# ---------------------------------------------------------------------------
Write-Step "Копирование проекта PF на p1"
if ($SkipProject) {
Write-Warn "Пропущено (-SkipProject)."
} else {
$rc = Start-Process -FilePath 'robocopy.exe' -ArgumentList @(
"`"$ProjectDir`"", "`"$($v1.DriveLetter):\`"", '/E', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS'
) -Wait -PassThru -NoNewWindow
if ($rc.ExitCode -ge 8) { throw "robocopy завершился с кодом $($rc.ExitCode)." }
Write-Ok "Проект скопирован на $($v1.DriveLetter):"
}
# ---------------------------------------------------------------------------
Write-Step "Копирование VTOYEFI на p2"
Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "$($v2.DriveLetter):\" -Recurse -Force -ErrorAction Stop
if (-not (Test-Path "$($v2.DriveLetter):\ventoy\ventoy.cpio")) { throw "VTOYEFI скопирован не полностью." }
Copy-Item -Path $coreImg -Destination "$($v2.DriveLetter):\ventoy\core.img" -Force -ErrorAction Stop
Write-Ok "VTOYEFI + core.img -> $($v2.DriveLetter):"
# ---------------------------------------------------------------------------
Write-Step "Артефакты в папке проекта на p1"
$projFolder = "$($v1.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 = "$($v1.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 "Активный раздел p1"
Set-Partition -DiskNumber $DiskNumber -PartitionNumber 1 -IsActive $true -ErrorAction Stop
Write-Ok "p1 помечен активным."
# ---------------------------------------------------------------------------
Write-Step "Проверка разметки"
$chk = Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset
$chk | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type -AutoSize
$c1 = $chk | Where-Object PartitionNumber -eq 1
$c2 = $chk | Where-Object PartitionNumber -eq 2
if ($c1.Offset -ne $P1Offset) { Write-Warn "p1 offset $($c1.Offset) != 1048576." }
if ($c2.Offset -ne ($c1.Offset + $c1.Size)) { Write-Warn "p2 не сразу после p1." }
if ($c2.Size -ne $VentoySize) { Write-Warn "p2 size $($c2.Size) != 33554432." }
Write-Step "Готово. Что делать дальше"
$msg = @"
Разметка:
p1 {0}: FAT32 проект + ISO
p2 {1}: FAT 32 МБ VTOYEFI
p3 {2}: NTFS ESD
Далее:
1) Запустите {0}:\Change_bootLoader.exe и выберите нужные загрузчики
(Legacy + UEFI). Он поставит MBR/PBR.
2) BIOS: добавьте пункт Xorboot на файл
\efi\Paravis\Boot\g4d\Ventoy
(или в menu.lst: find --set-root /ventoy/core.img; kernel /ventoy/core.img).
3) UEFI: добавьте в Xorboot загрузку файла
p2 {1}: \EFI\BOOT\BOOTX64.EFI
4) Распакуйте 3_PF_WindowsESD.zip на p3 {2}: (NTFS).
5) ISO: Ventoy ищет их только на p1 {0}:. Если p1 заполнен проектом,
положите ISO на p3 {2}: и создайте на p1 файлы-ссылки .vlnk.iso
через VentoyVlnk.exe из пакета Ventoy. Ventoy покажет ссылки в меню.
Если p1 позже переполнится — увеличьте P1SizeGB (до 32) и повторите разметку.
"@ -f $v1.DriveLetter, $v2.DriveLetter, $v3.DriveLetter
Write-Host $msg -ForegroundColor Gray
Write-Ok "Готово."
+43
View File
@@ -0,0 +1,43 @@
# Deploy everything staged on D: to the flash (p1 GRUB2 loader + p2 Ventoy cfg).
$ErrorActionPreference = 'Stop'
$src = 'C:\PF\ParavisGrub'
$g2 = 'F:\efi\Paravis\Boot\grub2'
$ven = 'C:\PF\Ventoy\vtoyefi\grub\grub.cfg'
function Fail($m) { Write-Host "ERROR: $m"; exit 1 }
if (-not (Test-Path 'F:\efi\Paravis\Boot')) { Fail 'p1 (F:) not available - VM may hold the disk' }
if (-not (Test-Path 'G:\grub\grub.cfg')) { Fail 'p2 (G:) not available - VM may hold the disk' }
New-Item -ItemType Directory -Force "$g2\menu", "$g2\apps" | Out-Null
# --- p1: our loader tree only
Copy-Item "$src\grub.cfg" "$g2\grub.cfg" -Force
Copy-Item "$src\menu\*.cfg" "$g2\menu\" -Force
Copy-Item "$src\apps\super.efi" "$g2\apps\super.efi" -Force
Copy-Item "$src\apps\memtest86p.efi" "$g2\apps\memtest86p.efi" -Force
foreach ($stale in 'memtest.efi','memtest86.efi') {
Remove-Item "$g2\apps\$stale" -Force -ErrorAction SilentlyContinue
}
# --- p2: Ventoy config (language default + earlier patches), backup first
Copy-Item 'G:\grub\grub.cfg' 'C:\PF\Ventoy\backup\grub.cfg.before-ru-default' -Force
Copy-Item $ven 'G:\grub\grub.cfg' -Force
# --- report
'=== p1 grub2 tree:'
Get-ChildItem $g2 -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$g2\",'')}},Length |
Sort-Object rel | Format-Table -AutoSize
'=== p2 ventoy cfg:'
'{0} bytes {1}' -f (Get-Item 'G:\grub\grub.cfg').Length, (Get-FileHash 'G:\grub\grub.cfg' -Algorithm SHA256).Hash.ToLower()
'{0} bytes {1}' -f (Get-Item $ven).Length, (Get-FileHash $ven -Algorithm SHA256).Hash.ToLower()
Select-String -Path 'G:\grub\grub.cfg' -Pattern 'vt_init_menu_lang' | ForEach-Object { ' ' + $_.Line.Trim() }
'=== syntax:'
$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe'
Get-ChildItem "$g2\grub.cfg", "$g2\menu\*.cfg" | ForEach-Object {
& $checker $_.FullName
if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" }
}
+26
View File
@@ -0,0 +1,26 @@
# Deploy Paravis GRUB menu + apps from D: staging to p1.
$src = 'C:\PF\ParavisGrub'
$dst = 'F:\efi\Paravis\Boot\grub2'
New-Item -ItemType Directory -Force "$dst\menu" | Out-Null
New-Item -ItemType Directory -Force "$dst\apps" | Out-Null
Copy-Item "$src\grub.cfg" "$dst\grub.cfg" -Force
Copy-Item "$src\menu\*.cfg" "$dst\menu\" -Force
Copy-Item "$src\apps\memtest86p.efi" "$dst\apps\memtest86p.efi" -Force
Remove-Item "$dst\apps\memtest86.efi" -Force -ErrorAction SilentlyContinue
'--- deployed tree:'
Get-ChildItem $dst -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$dst\",'')}},Length | Sort-Object rel | Format-Table -AutoSize
'--- syntax check:'
$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe'
Get-ChildItem "$dst\grub.cfg", "$dst\menu\*.cfg" | ForEach-Object {
& $checker $_.FullName
if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" }
}
'--- main menu head:'
Get-Content "$dst\grub.cfg" -TotalCount 6 | ForEach-Object { ' ' + $_ }
'--- submenu timeouts:'
Get-ChildItem "$dst\menu\*.cfg" | ForEach-Object { ' {0,-14} {1}' -f $_.Name, ((Get-Content $_.FullName -TotalCount 1)) }
+30
View File
@@ -0,0 +1,30 @@
# Deploy GRUB2 theme + menus to p1.
$ErrorActionPreference = 'Stop'
$src = 'C:\PF\ParavisGrub'
$dst = 'F:\efi\Paravis\Boot\grub2'
if (-not (Test-Path 'F:\efi\Paravis\Boot')) { 'p1 not available'; exit 1 }
# themes
Remove-Item "$dst\theme" -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force "$dst\theme" | Out-Null
Copy-Item "$src\theme\*" "$dst\theme\" -Recurse -Force
Remove-Item "$dst\theme\*\preview.png" -Force -ErrorAction SilentlyContinue
Remove-Item "$dst\theme\main\sel_bar.png" -Force -ErrorAction SilentlyContinue
# menus
Copy-Item "$src\grub.cfg" "$dst\grub.cfg" -Force
New-Item -ItemType Directory -Force "$dst\menu" | Out-Null
Copy-Item "$src\menu\*.cfg" "$dst\menu\" -Force
'--- tree:'
Get-ChildItem $dst -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$dst\",'')}},Length |
Sort-Object rel | Format-Table -AutoSize
'--- syntax:'
$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe'
Get-ChildItem "$dst\grub.cfg", "$dst\menu\*.cfg" | ForEach-Object {
& $checker $_.FullName
if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" }
}
'--- free on F: {0:N0} MB' -f ((Get-Volume -DriveLetter F).SizeRemaining / 1MB)
@@ -0,0 +1,19 @@
# Deploy the patched Ventoy grub.cfg (Russian default language) to p2.
$src = 'C:\PF\Ventoy\vtoyefi\grub\grub.cfg'
$dst = 'G:\grub\grub.cfg'
$bkp = 'C:\PF\Ventoy\backup\grub.cfg.before-ru-default'
if (Test-Path $dst) {
Copy-Item $dst $bkp -Force
Copy-Item $src $dst -Force
'disk : {0} bytes {1}' -f (Get-Item $dst).Length, (Get-FileHash $dst -Algorithm SHA256).Hash.ToLower()
'source: {0} bytes {1}' -f (Get-Item $src).Length, (Get-FileHash $src -Algorithm SHA256).Hash.ToLower()
'--- check:'
Select-String -Path $dst -Pattern 'vt_init_menu_lang' | ForEach-Object { ' ' + $_.Line.Trim() }
'--- other patches still present:'
foreach ($s in 'VTOY_DATA_PART_IDX', 'ISO/Ventoy/ventoy.json', 'SSTR/BCD') {
' {0}: {1}' -f $s, (Select-String -Path $dst -Pattern ([regex]::Escape($s)) | Measure-Object).Count
}
} else {
'G: not available'
}
+247
View File
@@ -0,0 +1,247 @@
#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
+61
View File
@@ -0,0 +1,61 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Готовит VMware VM к загрузке Ventoy с raw-диска:
сбрасывает NVRAM (boot-записи) и, при -SecureBoot Off, выключает SB в VM.
.PARAMETER Vmx
Путь к .vmx.
.PARAMETER SecureBoot
On/Off. По умолчанию Off (для первого теста; сертификат Ventoy в NVRAM VM
не импортирован, при On потребуется MokManager).
#>
[CmdletBinding()]
param(
[string]$Vmx = 'D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx',
[ValidateSet('On', 'Off')]
[string]$SecureBoot = 'Off'
)
$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 }
if (-not (Test-Path $Vmx)) { throw "Нет файла: $Vmx" }
$dir = Split-Path $Vmx
$vmxProc = Get-Process -Name 'vmware-vmx' -ErrorAction SilentlyContinue
if ($vmxProc) { throw "VM запущена. Выключите её." }
Write-Step "Бэкап VMX"
$bak = "$Vmx.bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date)
Copy-Item $Vmx $bak -Force
Write-Ok $bak
Write-Step "Secure Boot = $SecureBoot"
$txt = Get-Content $Vmx -Raw -Encoding UTF8
if ($SecureBoot -eq 'Off') {
if ($txt -match 'uefi\.secureBoot\.enabled') {
$txt = $txt -replace 'uefi\.secureBoot\.enabled\s*=\s*"[^"]*"', 'uefi.secureBoot.enabled = "FALSE"'
} else {
$txt = $txt.TrimEnd() + "`nuefi.secureBoot.enabled = `"FALSE`"`n"
}
} else {
$txt = $txt -replace 'uefi\.secureBoot\.enabled\s*=\s*"[^"]*"', 'uefi.secureBoot.enabled = "TRUE"'
}
[IO.File]::WriteAllText($Vmx, $txt, (New-Object System.Text.UTF8Encoding($false)))
Write-Ok "записано"
Write-Step "Сброс NVRAM"
Get-ChildItem $dir -Filter '*.nvram' | ForEach-Object {
$b = "$($_.FullName).bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date)
Copy-Item $_.FullName $b -Force
Remove-Item $_.FullName -Force
Write-Ok ("удалён {0} (бэкап {1})" -f $_.Name, (Split-Path $b -Leaf))
}
Write-Step "Диски VM"
Select-String -Path $Vmx -Pattern '^(sata|nvme|scsi|ide).*(fileName|deviceType)|^firmware|secureBoot' |
Select-Object -ExpandProperty Line
@@ -0,0 +1,70 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Убирает из VMware VM второй raw-диск (nvme0:0), указывающий на тот же
\\.\PhysicalDrive2, что и sata0:0. Плюс чистит устаревшие .lck.
.DESCRIPTION
VMware не может открыть один физический диск дважды — отсюда
"Операция с файлом \\.\PhysicalDrive2 не удалась".
Скрипт:
1. проверяет, что VM не запущена (нет процесса vmware-vmx);
2. делает бэкап .vmx;
3. удаляет строки nvme0.*;
4. удаляет устаревшие каталоги *.lck;
5. печатает оставшиеся диски.
.PARAMETER Vmx
Путь к .vmx. По умолчанию "D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx".
#>
[CmdletBinding()]
param(
[string]$Vmx = 'D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx'
)
$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 }
if (-not (Test-Path $Vmx)) { throw "Нет файла: $Vmx" }
$dir = Split-Path $Vmx
Write-Step "Проверка, что VM не запущена"
$vmxProc = Get-Process -Name 'vmware-vmx' -ErrorAction SilentlyContinue
if ($vmxProc) {
throw "VM запущена (vmware-vmx PID $($vmxProc.Id -join ',')). Выключите её и повторите."
}
Write-Ok "vmware-vmx не запущен."
Write-Step "Бэкап"
$bak = "$Vmx.bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date)
Copy-Item $Vmx $bak -Force
Write-Ok "бэкап: $bak"
Write-Step "Удаление nvme0:* из VMX"
$lines = Get-Content $Vmx -Encoding UTF8
$keep = $lines | Where-Object { $_ -notmatch '^nvme0' }
$removed = $lines.Count - $keep.Count
if ($removed -eq 0) {
Write-Warn "строк nvme0 не найдено — возможно, уже убрано."
} else {
$utf8 = New-Object System.Text.UTF8Encoding($false)
[IO.File]::WriteAllLines($Vmx, $keep, $utf8)
Write-Ok ("удалено строк: {0}" -f $removed)
}
Write-Step "Удаление устаревших .lck"
Get-ChildItem $dir -Directory -Filter '*.lck' -ErrorAction SilentlyContinue | ForEach-Object {
Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue
Write-Ok ("удалён {0}" -f $_.Name)
}
Write-Step "Текущие диски в VMX"
Select-String -Path $Vmx -Pattern 'present = "TRUE"|fileName|deviceType' |
Where-Object { $_.Line -match '^(sata|nvme|scsi|ide)' } |
Select-Object -ExpandProperty Line
Write-Step "Готово"
Write-Host "Запускайте VM. Должен остаться один raw-диск (sata0:0 -> Windows 10-1.vmdk)." -ForegroundColor Green
+374
View File
@@ -0,0 +1,374 @@
#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
}
+271
View File
@@ -0,0 +1,271 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Готовит НОВУЮ флешку (64 ГБ) под кастомную схему:
p1 = загрузочный FAT32 (PARAVIS) + Xorboot MBR,
p2 = VTOYEFI 32 МБ,
p3 = данные NTFS (DATA) с ISO.
.DESCRIPTION
Диск полностью очищается (diskpart clean) — всё содержимое теряется.
Источники:
* проект : E:\_usb_stage\PARAVIS (staging со старого SSD)
* VTOYEFI : C:\PF\Ventoy\vtoyefi + core-custom-layout-1.1.18.img
* ISO : E:\Downloads\ISO
* маркер : E:\_usb_stage\ISO_Ventoy -> \ISO\Ventoy
В конце ставится Xorboot MBR/PBR через bootice (/keep_dpt, /keep_bpb)
и проверяется, что код MBR совпадает с xmbr.bin.
.EXAMPLE
.\prepare-new-usb.ps1 -WhatIf
.\prepare-new-usb.ps1 -DiskNumber 2
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[int]$DiskNumber = 0,
[int]$BootSizeMB = 14336,
[int]$TailMB = 50,
[string]$StageDir = 'E:\_usb_stage',
[string]$IsoSource = 'E:\Downloads\ISO',
[string]$VentoyDir = 'C:\PF\Ventoy',
[string]$BackupDir = 'C:\PF\Ventoy\backup',
[string]$Serial = 'AA00000000000489',
[switch]$Force
)
$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-Diskpart([string]$script) {
$tmp = Join-Path $env:TEMP ("dp_{0}.txt" -f ([guid]::NewGuid().ToString('N')))
$script | Set-Content -Path $tmp -Encoding ASCII
$out = & diskpart.exe /s $tmp 2>&1
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
$out | ForEach-Object { " $_" }
if ($LASTEXITCODE -ne 0) { throw "diskpart завершился с кодом $LASTEXITCODE" }
}
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 { } }
}
# ------------------------------------------------------------------ диск
Write-Step "Выбор диска"
if ($DiskNumber -gt 0) {
$disk = Get-Disk -Number $DiskNumber
} else {
$cand = @(Get-Disk | Where-Object {
$_.BusType -eq 'USB' -and
$_.Size -ge 40GB -and $_.Size -le 100GB -and
-not $_.IsBoot -and -not $_.IsSystem
})
if ($cand.Count -ne 1) {
$cand | Select-Object Number,FriendlyName,SerialNumber,@{n='GB';e={[math]::Round($_.Size/1GB,1)}} | Format-Table -AutoSize | Out-String | Write-Host
throw "Не удалось однозначно выбрать диск — укажите -DiskNumber."
}
$disk = $cand[0]
}
if ($disk.BusType -ne 'USB') { throw "Диск $($disk.Number) не USB ($($disk.BusType))." }
if ($disk.IsBoot -or $disk.IsSystem) { throw "Это системный диск — отказ." }
if (-not $Force -and $Serial -and $disk.SerialNumber -and $disk.SerialNumber.Trim() -ne $Serial) {
throw ("Серийный номер '{0}' не совпал с ожидаемым '{1}'. Если уверены — -Force." -f $disk.SerialNumber, $Serial)
}
$diskNum = $disk.Number
Write-Host (" Диск {0}: {1}, {2:N2} ГиБ ({3} МБ), {4}, serial={5}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), ([math]::Floor($disk.Size/1MB)), $disk.PartitionStyle, $disk.SerialNumber)
Write-Host " ВНИМАНИЕ: диск будет полностью очищен." -ForegroundColor Red
$cur = Get-Partition -DiskNumber $diskNum -ErrorAction SilentlyContinue
if ($cur) {
$cur | Select-Object PartitionNumber, DriveLetter, Offset, @{n='GB';e={[math]::Round($_.Size/1GB,2)}}, Type | Format-Table -AutoSize | Out-String | Write-Host
}
# --------------------------------------------------------------- источники
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" }
if (-not (Test-Path $stageIsoVentoy)) { throw "Нет \ISO\Ventoy в staging: $stageIsoVentoy" }
$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))
$p1Bytes = [int64]$BootSizeMB * 1MB
$p2Bytes = [int64]32 * 1MB
$p3Bytes = $disk.Size - $p1Bytes - $p2Bytes - ([int64]$TailMB * 1MB)
if ($p3Bytes -le 0) { throw "Диск слишком мал для выбранных размеров." }
Write-Host (" p1 {0:N2} ГиБ / p2 32 МиБ / p3 {1:N2} ГиБ" -f ($p1Bytes/1GB), ($p3Bytes/1GB))
if ($projBytes -gt ($p1Bytes - 64MB)) { throw "Проект не помещается на p1." }
if ($isoBytes -gt ($p3Bytes - 256MB)) { throw "ISO не помещаются на p3." }
if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum ($($disk.FriendlyName))", "Стереть диск и создать: p1 ${BootSizeMB}MB FAT32 PARAVIS, p2 32MB VTOYEFI, p3 NTFS DATA")) {
Write-Warn "WhatIf: изменения не вносились."
return
}
# ------------------------------------------------------------------ backup
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
$bkpFile = Join-Path $BackupDir ("usb-new-{0}-{1:yyyyMMdd-HHmmss}.bin" -f $diskNum, (Get-Date))
[IO.File]::WriteAllBytes($bkpFile, (Read-Raw $diskNum 65536))
Write-Ok ("первые 64 КиБ сохранены: {0}" -f $bkpFile)
# ------------------------------------------------------------- разметка
Write-Step "Разметка (diskpart clean)"
$p3MB = [math]::Floor($p3Bytes / 1MB)
$dp = @"
select disk $diskNum
clean
create partition primary size=$BootSizeMB
format fs=fat32 quick label=PARAVIS
active
assign
create partition primary size=32
format fs=fat quick label=VTOYEFI
assign
create partition primary size=$p3MB
format fs=ntfs quick label=DATA
assign
exit
"@
Invoke-Diskpart $dp
Write-Ok "Разделы созданы."
Write-Step "Обновление таблицы устройств"
Update-HostStorageCache
Start-Sleep -Seconds 3
$deadline = (Get-Date).AddSeconds(60)
do {
Update-HostStorageCache
$v1 = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$v2 = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$v3 = Get-DiskVolumeLabel $diskNum 'DATA'
if ($v1 -and $v2 -and $v3) { break }
Start-Sleep -Seconds 2
} while ((Get-Date) -lt $deadline)
if (-not ($v1 -and $v2 -and $v3)) { throw "Новые разделы не появились." }
foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) {
Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter
}
Start-Sleep -Seconds 1
Update-HostStorageCache
$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$pData = Get-DiskVolumeLabel $diskNum 'DATA'
if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) {
throw "Не всем разделам назначены буквы."
}
Write-Ok ("буквы: PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter)
$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset
$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host
if ($geo[0].Offset -ne 1048576) { throw "p1 начинается не с 1 МиБ." }
if ($geo[0].Size -ne $p1Bytes) { throw "p1 неверного размера." }
if ($geo[1].Offset -ne ($geo[0].Offset + $geo[0].Size)) { throw "p2 не сразу за p1." }
if ($geo[1].Size -ne $p2Bytes) { throw "p2 не 32 МБ." }
if (-not $geo[0].IsActive) { throw "p1 не active." }
Write-Ok "Геометрия корректна."
# ---------------------------------------------------------------- файлы
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 "grub.cfg без VTOY-CUSTOM-LAYOUT." }
Write-Ok ("VTOYEFI + core ({0} Б)" -f (Get-Item $coreImg).Length)
Write-Step "ISO -> p3"
Invoke-Robocopy $IsoSource ("{0}:\ISO" -f $pData.DriveLetter) | Out-Null
Invoke-Robocopy $stageIsoVentoy ("{0}:\ISO\Ventoy" -f $pData.DriveLetter) | Out-Null
if (-not (Test-Path ("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter))) { throw "Маркер NOT.DEL не создан." }
Write-Ok "ISO и маркер на месте."
# --------------------------------------------------------------- Xorboot
Write-Step "Установка Xorboot (MBR + PBR)"
$bootice = ("{0}:\efi\Paravis\Boot\bootice.exe" -f $pProj.DriveLetter)
$xmbr = ("{0}:\efi\Paravis\Boot\xor\xmbr.bin" -f $pProj.DriveLetter)
$xpbr = ("{0}:\efi\Paravis\Boot\xor\xpbr.bin" -f $pProj.DriveLetter)
foreach ($f in @($bootice, $xmbr, $xpbr)) { if (-not (Test-Path $f)) { throw "Нет файла: $f" } }
$dev = ("{0}:" -f $pProj.DriveLetter)
& $bootice "/DEVICE=$dev" /mbr /restore "/file=$xmbr" /keep_dpt /quiet | Out-Host
& $bootice "/DEVICE=$dev" /pbr /restore "/file=$xpbr" /keep_bpb /quiet | Out-Host
Start-Sleep -Seconds 1
Write-Ok "bootice: MBR и PBR записаны."
Write-Step "Проверка MBR"
$mbr = Read-Raw $diskNum 512
$xmbrBytes = [IO.File]::ReadAllBytes($xmbr)
# bootice с /keep_dpt сохраняет таблицу разделов (0x1BE..0x1FD) и подпись диска
# (0x1B8..0x1BB), поэтому сравниваем код до и после этого участка.
$same = $true
for ($i = 0; $i -lt 0x1B8; $i++) { if ($mbr[$i] -ne $xmbrBytes[$i]) { $same = $false; break } }
if ($same) {
for ($i = 0x1BC; $i -lt 0x1BE; $i++) { if ($mbr[$i] -ne $xmbrBytes[$i]) { $same = $false; break } }
}
if ($same) {
Write-Ok "Код MBR совпадает с xmbr.bin."
} else {
Write-Warn "Код MBR отличается от xmbr.bin — проверьте загрузку; при необходимости Change_bootLoader.exe -> Install XorBoot."
}
$sig = "{0:X2}{1:X2}" -f $mbr[510], $mbr[511]
Write-Host (" сигнатура MBR: {0}, active p1: {1}" -f $sig, $geo[0].IsActive)
# ---------------------------------------------------------------- отчёт
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\\' } | Measure-Object Length -Sum
" p1 {0}: {1:N2} ГБ, {2} файлов (источник {3:N2} ГБ)" -f $pProj.DriveLetter, ($projDst.Sum/1GB), $projDst.Count, ($projBytes/1GB)
" p2 {0}: core {1} Б" -f $pEfi.DriveLetter, (Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length
" p3 {0}: ISO {1} шт., {2:N2} ГБ (источник {3:N2} ГБ)" -f $pData.DriveLetter, $isoDst.Count, ($isoDstBytes/1GB), ($isoBytes/1GB)
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
@@ -0,0 +1,250 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Подготавливает на флешке второй раздел 32 МБ (VTOYEFI) для Ventoy,
НЕ трогая MBR-код и первый раздел с проектом Paravis.
.DESCRIPTION
Схема, которую требует стоковый Ventoy:
p1: начинается с LBA 2048 (1 МБ), содержит ваши файлы и ISO
p2: 65536 секторов (32 МБ), FAT, сразу после p1, содержит VTOYEFI + /ventoy/core.img
Скрипт:
1. проверяет, что диск USB, MBR, p1 — единственный/последний раздел;
2. при необходимости уменьшает p1 на 32 МБ (плюс до 1 МБ на выравнивание;
файловая система, не начало!);
3. создаёт p2 сразу после p1 и форматирует его в FAT;
4. копирует туда распакованный VTOYEFI и core.img;
5. кладёт core.img и grldr-ventoy в папку проекта на p1.
MBR-загрузочный код (xorboot/grub4dos) не перезаписывается.
Таблица разделов обновляется штатными средствами Windows.
.PARAMETER DiskNumber
Номер физического диска из Get-Disk. Например: 2.
.PARAMETER SourceDir
Папка с распакованными материалами Ventoy (vtoyefi, ventoy-1.1.18, core.img).
.PARAMETER AllowNonUsb
Разрешить не-USB диск (только для тестов на VHD; на реальной системе не используйте).
.EXAMPLE
.\prepare-ventoy-partition.ps1 -DiskNumber 2 -WhatIf
.EXAMPLE
.\prepare-ventoy-partition.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 — обязательное требование Ventoy
$Label = 'VTOYEFI'
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 }
# ---------------------------------------------------------------------------
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). Legacy core.img Ventoy рассчитан на msdos-разметку."
}
$parts = @(Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset)
$p1 = $parts | Where-Object { $_.PartitionNumber -eq 1 }
if (-not $p1) { throw "На диске нет раздела 1." }
$extra = @($parts | Where-Object { $_.PartitionNumber -ne 1 })
if ($extra.Count -gt 0) {
$list = ($extra | ForEach-Object { "p$($_.PartitionNumber) offset=$($_.Offset) size=$($_.Size)" }) -join '; '
throw "На диске уже есть другие разделы: $list. Нужен диск, где p1 — последний раздел (Ventoy требует p2 сразу после p1)."
}
Write-Host ("Диск: {0}, {1:N1} GB, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle, $disk.BusType)
Write-Host ("p1: offset={0} (LBA {1}), size={2:N1} MB" -f $p1.Offset, ($p1.Offset/512), ($p1.Size/1MB))
if ($p1.Offset -ne $P1Offset) {
Write-Warn ("p1 начинается с offset {0} (LBA {1}), а Ventoy ожидает 2048 (1 МБ)." -f $p1.Offset, ($p1.Offset/512))
Write-Warn "Ventoy сможет загрузиться, но выведет предупреждение 'This is NOT a standard Ventoy device'."
Write-Warn "Правильнее пересобрать флешку с p1 на LBA 2048 (файлы проекта у вас есть в C:\PF\PF)."
if (-not $PSCmdlet.ShouldContinue("Продолжить несмотря на нестандартное начало p1?", "Нестандартная разметка")) {
throw "Отменено пользователем."
}
}
$vol = Get-Volume -Partition $p1 -ErrorAction Stop
if (-not $vol.DriveLetter) {
throw "У раздела p1 нет буквы диска. Назначьте букву и повторите."
}
$p1Letter = $vol.DriveLetter
$p1End = $p1.Offset + $p1.Size
$tailFree = $disk.Size - $p1End
if ($tailFree -lt 0) { throw "Некорректная геометрия: p1 выходит за пределы диска." }
# p2 должен начинаться ровно в конце p1. Windows по умолчанию выравнивает
# новые разделы на 1 МБ, поэтому конец p1 тоже выравниваем на 1 МБ.
$align = 1MB
$maxP1End = [Math]::Floor(($disk.Size - $VentoySize) / $align) * $align
$targetP1End = [Math]::Min($p1End, $maxP1End)
$targetP1End = [Math]::Floor($targetP1End / $align) * $align
if ($targetP1End -le $p1.Offset) { throw "Недостаточно места: p1 нельзя уменьшить до 1-МБ границы." }
$newP1Size = $targetP1End - $p1.Offset
$shrink = $p1.Size - $newP1Size
if ($shrink -lt 0) { throw "Внутренняя ошибка: p2 оказался бы внутри p1." }
if ($shrink -gt 0) {
if ($vol.SizeRemaining -lt $shrink) {
throw ("На p1 свободно {0:N1} MB, а для p2 нужно освободить {1:N1} MB. Освободите место на флешке." -f ($vol.SizeRemaining/1MB), ($shrink/1MB))
}
if ($p1.Size -le $shrink) { throw "p1 слишком мал." }
}
$p2Offset = $targetP1End
$p2End = $p2Offset + $VentoySize
if ($p2End -gt $disk.Size) { throw "p2 не помещается на диск." }
Write-Host ("План: p2 offset={0} (LBA {1}), size=32 MB, конец={2} (LBA {3})" -f $p2Offset, ($p2Offset/512), $p2End, ($p2End/512))
if ($shrink -gt 0) {
Write-Host ("План: уменьшить p1 на {0:N1} MB (с {1:N1} MB до {2:N1} MB); начало p1 не меняется." -f ($shrink/1MB), ($p1.Size/1MB), ($newP1Size/1MB))
} else {
Write-Host "План: p1 уже выровнен, p2 создаётся сразу после p1."
}
if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "Уменьшить p1 при необходимости, создать p2 32MB, отформатировать FAT, скопировать VTOYEFI и core.img")) {
Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow
return
}
# ---------------------------------------------------------------------------
if ($shrink -gt 0) {
Write-Step "Уменьшение p1 на $([Math]::Round($shrink/1MB,1)) MB"
Write-Warn "Если p1 — FAT32/NTFS с данными у конца раздела, Windows может отказать. Файлы не удаляются, но сделайте бэкап."
Resize-Partition -DriveLetter $p1Letter -Size $newP1Size -ErrorAction Stop
Start-Sleep -Seconds 2
Write-Ok "p1 уменьшен. Новый размер: $([Math]::Round($newP1Size/1MB,1)) MB"
}
# ---------------------------------------------------------------------------
Write-Step "Создание p2 (32 MB) сразу после p1"
$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment $align -AssignDriveLetter -ErrorAction Stop
Start-Sleep -Seconds 1
$p2Vol = Get-Volume -Partition $p2 -ErrorAction Stop
Write-Ok "p2 создан: диск $($p2Vol.DriveLetter):, offset=$($p2.Offset), size=$($p2.Size)"
Write-Step "Форматирование p2 в FAT (Ventoy допускает FAT12/16/32)"
Format-Volume -DriveLetter $p2Vol.DriveLetter -FileSystem FAT -NewFileSystemLabel $Label -Confirm:$false -Force -ErrorAction Stop
Start-Sleep -Seconds 1
# ---------------------------------------------------------------------------
Write-Step "Копирование VTOYEFI"
$p2Root = "$($p2Vol.DriveLetter):\"
Copy-Item -Path (Join-Path $vtoyefi '*') -Destination $p2Root -Recurse -Force -ErrorAction Stop
if (-not (Test-Path (Join-Path $p2Root 'ventoy\ventoy.cpio'))) {
throw "После копирования не найден $p2Root\ventoy\ventoy.cpio"
}
Write-Ok "VTOYEFI скопирован."
Write-Step "Копирование core.img"
$coreDst = Join-Path $p2Root 'ventoy\core.img'
Copy-Item -Path $coreImg -Destination $coreDst -Force -ErrorAction Stop
Write-Ok "core.img -> $coreDst"
# ---------------------------------------------------------------------------
Write-Step "Артефакты в папке проекта на p1"
$projFolder = Join-Path "$($p1Letter):\" '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 "$($p1Letter):\" 'efi\Paravis\Boot\g4d'
if (Test-Path $g4d) {
Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force
Write-Ok "grldr-ventoy -> $g4d\Ventoy (для пункта Xorboot)"
}
}
Write-Ok "core.img и grldr-ventoy -> $projFolder"
# ---------------------------------------------------------------------------
Write-Step "Проверка разметки"
$p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1
$p2After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 2
$expectedP2Offset = $p1After.Offset + $p1After.Size
if ($p2After.Offset -ne $expectedP2Offset) {
Write-Warn ("p2 offset {0} != конец p1 {1}. Ventoy может отказаться." -f $p2After.Offset, $expectedP2Offset)
} else {
Write-Ok "p2 начинается ровно в конце p1."
}
if ($p2After.Size -ne $VentoySize) {
Write-Warn ("p2 size {0} != {1} (65536 секторов)." -f $p2After.Size, $VentoySize)
} else {
Write-Ok "p2 size = 32 MB (65536 секторов)."
}
if ($p1After.Offset -ne $P1Offset) {
Write-Warn ("p1 offset {0} != 1048576 (LBA 2048)." -f $p1After.Offset)
} else {
Write-Ok "p1 начинается с LBA 2048."
}
Write-Step "Готово. Что делать дальше"
Write-Host @"
1) BIOS / grub4dos. Добавьте пункт в menu.lst (или загрузите файл \efi\Paravis\Boot\g4d\Ventoy):
title Ventoy 1.1.18 (BIOS)
find --set-root /ventoy/core.img
kernel /ventoy/core.img
boot
2) UEFI / Xorboot. Добавьте загрузку файла со второго раздела (p2):
\EFI\BOOT\BOOTX64.EFI
(Secure Boot: при первом запуске согласиться с MOK и выбрать
ENROLL_THIS_KEY_IN_MOKMANAGER.cer с p2.)
3) ISO-файлы кладите на p1 (в любые папки). Ventoy ищет их на p1.
4) Проверка разметки:
Get-Partition -DiskNumber $DiskNumber | Format-Table PartitionNumber,Offset,Size
Должно быть: p1 offset=1048576, p2 сразу после p1, p2 size=33554432.
Откат: удалить p2 (Remove-Partition) и расширить p1 обратно:
Resize-Partition -DriveLetter $p1Letter -Size <старый_размер_p1>
"@ -ForegroundColor Gray
Write-Ok "MBR-код не изменялся. Таблица разделов обновлена штатно."
+365
View File
@@ -0,0 +1,365 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Пересоздаёт разметку USB-диска под кастомный Ventoy:
p1 = загрузочный FAT32 (PARAVIS), p2 = VTOYEFI 32 МБ, p3 = данные NTFS (DATA).
.DESCRIPTION
Порядок работы:
1. проверяет диск/разделы/источники;
2. копирует проект с загрузочного раздела в E:\_usb_stage;
3. сохраняет первые 64 КиБ диска (MBR Xorboot + gap);
4. удаляет разделы 3,2,1 и создаёт новые (p1 14 ГиБ FAT32 active,
p2 32 МБ FAT VTOYEFI, p3 остаток NTFS DATA);
5. возвращает на место байты 0..445 MBR (код Xorboot + подпись диска),
таблица разделов остаётся новой; проверяет сектора 1..62;
6. возвращает проект на p1, VTOYEFI на p2, ISO с E:\Downloads\ISO на p3,
создаёт \ISO\Ventoy (маркер NOT.DEL, README, theme).
Разметка НЕ стирается через diskpart clean — иначе пропал бы код Xorboot
в первых 63 секторах.
.PARAMETER BootSizeMB
Размер p1 в МБ. По умолчанию 14336 (14 ГиБ).
.PARAMETER TailMB
Неразмеченный хвост в МБ. По умолчанию 50.
.PARAMETER StageDir
Куда временно копируется проект. По умолчанию E:\_usb_stage.
.PARAMETER IsoSource
Откуда берутся ISO. По умолчанию E:\Downloads\ISO.
.PARAMETER VentoyDir
Папка с vtoyefi и core-custom-layout-1.1.18.img. По умолчанию C:\PF\Ventoy.
.PARAMETER SkipStage
Не копировать проект заново (уже лежит в StageDir).
.EXAMPLE
.\relayout-usb.ps1 -WhatIf
.\relayout-usb.ps1
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[int]$BootSizeMB = 14336,
[int]$TailMB = 50,
[int]$DiskNumber = 0,
[string]$StageDir = 'E:\_usb_stage',
[string]$IsoSource = 'E:\Downloads\ISO',
[string]$VentoyDir = 'C:\PF\Ventoy',
[string]$BackupDir = 'C:\PF\Ventoy\backup',
[switch]$SkipStage,
[switch]$Force
)
$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-Diskpart([string]$script) {
$tmp = Join-Path $env:TEMP ("dp_{0}.txt" -f ([guid]::NewGuid().ToString('N')))
$script | Set-Content -Path $tmp -Encoding ASCII
$out = & diskpart.exe /s $tmp 2>&1
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
$out | ForEach-Object { " $_" }
if ($LASTEXITCODE -ne 0) { throw "diskpart завершился с кодом $LASTEXITCODE" }
}
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 Open-Physical([int]$num) {
for ($i = 0; $i -lt 6; $i++) {
try {
return [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite, 4096, [IO.FileOptions]::WriteThrough)
} catch {
Start-Sleep -Seconds 2
}
}
throw "Не удалось открыть \\.\PhysicalDrive$num (занят другим процессом?)."
}
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
}
# ------------------------------------------------------------------ 1. диск
Write-Step "Поиск диска"
if ($DiskNumber -gt 0) {
$diskNum = $DiskNumber
Write-Host (" диск задан явно: {0}" -f $diskNum)
} else {
$efiVol = Get-Volume | Where-Object { $_.FileSystemLabel -eq 'VTOYEFI' } | Select-Object -First 1
if ($efiVol -and $efiVol.DriveLetter) {
$diskNum = (Get-Partition -DriveLetter $efiVol.DriveLetter).DiskNumber
} else {
$cand = @(Get-Disk | Where-Object { $_.BusType -eq 'USB' -and $_.PartitionStyle -eq 'MBR' -and $_.Size -eq 512110190592 })
if ($cand.Count -ne 1) { throw "Не удалось однозначно определить диск. Укажите -DiskNumber (см. Get-Disk)." }
$diskNum = $cand[0].Number
Write-Warn "Метка VTOYEFI не найдена, диск выбран по размеру/типу."
}
}
$disk = Get-Disk -Number $diskNum
$projVol = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$dataVol = Get-DiskVolumeLabel $diskNum 'DATA'
$efiVol = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
if (-not $SkipStage) {
if (-not $projVol -or -not $projVol.DriveLetter) { throw "Не найден раздел PARAVIS." }
if (-not $dataVol -or -not $dataVol.DriveLetter) { throw "Не найден раздел DATA." }
}
Write-Host (" Диск {0}: {1}, {2:N1} ГиБ, {3}, USB={4}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle, $disk.BusType)
Write-Host (" PARAVIS = {0} DATA = {1} VTOYEFI = {2}" -f $(if($projVol){$projVol.DriveLetter}else{'-'}), $(if($dataVol){$dataVol.DriveLetter}else{'-'}), $(if($efiVol){$efiVol.DriveLetter}else{'-'}))
if ($disk.PartitionStyle -ne 'MBR') { throw "Ожидалась MBR-разметка, найдена $($disk.PartitionStyle)." }
if (-not $Force -and $disk.Size -ne 512110190592) {
throw ("Неожиданный размер диска {0} (ожидался 512110190592). Если уверены — -Force." -f $disk.Size)
}
$parts = Get-Partition -DiskNumber $diskNum | Sort-Object Offset
if (-not $SkipStage -and $parts.Count -ne 3) { throw "Ожидалось 3 раздела, найдено $($parts.Count)." }
# --------------------------------------------------------------- 2. источники
Write-Step "Проверка источников"
if (-not (Test-Path $IsoSource)) { throw "Нет папки с ISO: $IsoSource" }
$isos = Get-ChildItem $IsoSource -File -Filter *.iso
if ($isos.Count -eq 0) { throw "В $IsoSource нет ISO." }
$isoBytes = ($isos | Measure-Object Length -Sum).Sum
Write-Host (" ISO: {0} шт., {1:N2} ГБ" -f $isos.Count, ($isoBytes/1GB))
$vtoyefi = Join-Path $VentoyDir 'vtoyefi'
$coreImg = Join-Path $VentoyDir '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" }
if (-not (Select-String -Path (Join-Path $vtoyefi 'grub\grub.cfg') -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) {
throw "grub.cfg в vtoyefi не содержит кастомный поиск раздела (VTOY-CUSTOM-LAYOUT)."
}
# ------------------------------------------------------------------ 3. stage
$stageProj = Join-Path $StageDir 'PARAVIS'
$stageIsoVentoy = Join-Path $StageDir 'ISO_Ventoy'
$projSrcSize = $null
if ($projVol -and $projVol.DriveLetter) {
$projSrcSize = (Get-ChildItem ("{0}:\" -f $projVol.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\System Volume Information\\' -and $_.FullName -notmatch '\\\$RECYCLE\.BIN\\' -and $_.Name -ne 'ventoy.log' } |
Measure-Object Length -Sum)
}
if (-not $SkipStage -and (Test-Path $stageProj)) {
$existing = Get-ChildItem $stageProj -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum
if ($null -eq $projSrcSize -or $existing.Sum -eq $projSrcSize.Sum) {
Write-Step "Staging уже готов (размер совпадает) — копирование пропущено"
$SkipStage = $true
}
}
if ($SkipStage) {
Write-Step "Staging пропущен (-SkipStage)"
} else {
if (-not $projVol -or -not $projVol.DriveLetter) { throw "Нет раздела PARAVIS для staging (укажите -SkipStage, если staging уже готов)." }
$stageRoot = [IO.Path]::GetPathRoot($StageDir).TrimEnd('\').TrimEnd(':')
$free = (Get-Volume | Where-Object { $_.DriveLetter -and ([string]$_.DriveLetter) -eq $stageRoot } | Select-Object -First 1).SizeRemaining
if ($free -lt ($projSrcSize.Sum + 2GB)) {
throw ("На {0} недостаточно места: нужно {1:N1} ГБ, свободно {2:N1} ГБ." -f $stageRoot, (($projSrcSize.Sum+2GB)/1GB), ($free/1GB))
}
Write-Step "Копирование загрузочного раздела в staging"
Write-Host (" {0:N2} ГБ -> {1}" -f ($projSrcSize.Sum/1GB), $stageProj)
if (Test-Path $stageProj) { Remove-Item $stageProj -Recurse -Force }
Invoke-Robocopy ("{0}:\" -f $projVol.DriveLetter) $stageProj @('/XD', 'System Volume Information', '$RECYCLE.BIN', '/XF', 'ventoy.log') | Out-Null
$stageSize = (Get-ChildItem $stageProj -Recurse -File -Force | Measure-Object Length -Sum)
Write-Host (" скопировано: {0:N2} ГБ, {1} файлов" -f ($stageSize.Sum/1GB), $stageSize.Count)
if ($stageSize.Sum -ne $projSrcSize.Sum) {
throw ("Размер копии не совпал: {0} != {1}. Разметка НЕ менялась." -f $stageSize.Sum, $projSrcSize.Sum)
}
Write-Ok "Проект скопирован и сверен."
if (Test-Path ("{0}:\ISO\Ventoy" -f $dataVol.DriveLetter)) {
if (Test-Path $stageIsoVentoy) { Remove-Item $stageIsoVentoy -Recurse -Force }
Invoke-Robocopy ("{0}:\ISO\Ventoy" -f $dataVol.DriveLetter) $stageIsoVentoy | Out-Null
Write-Ok "\ISO\Ventoy сохранён в staging."
}
}
# ------------------------------------------------------------- 4. bkp + wipe
if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum", "Переразметить: p1 ${BootSizeMB}MB FAT32, p2 32MB FAT VTOYEFI, p3 NTFS DATA")) {
Write-Warn "WhatIf: изменения не вносились."
return
}
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
$mbrFile = Join-Path $BackupDir ("usb-mbr-{0:yyyyMMdd-HHmmss}.bin" -f (Get-Date))
Write-Step "Сохранение первых 64 КиБ диска"
$head = New-Object byte[] 65536
$fs = Open-Physical $diskNum
try {
$read = $fs.Read($head, 0, $head.Length)
if ($read -ne $head.Length) { throw "Прочитано $read байт вместо 65536." }
} finally { try { $fs.Close() } catch { } }
[IO.File]::WriteAllBytes($mbrFile, $head)
Write-Ok ("MBR/gap сохранены: {0}" -f $mbrFile)
Write-Step "Снятие букв (best effort)"
foreach ($l in @($projVol.DriveLetter, $dataVol.DriveLetter, $efiVol.DriveLetter)) {
if ($l) { & mountvol.exe ("{0}:" -f $l) /p 2>$null | Out-Null }
}
Write-Step "Переразметка (diskpart)"
$totalMB = [math]::Floor($disk.Size / 1MB)
$p3MB = $totalMB - $BootSizeMB - 32 - $TailMB
if ($p3MB -lt 1024) { throw "Слишком маленький диск для выбранных размеров." }
$dp = @"
select disk $diskNum
select partition 3
delete partition override
select partition 2
delete partition override
select partition 1
delete partition override
create partition primary size=$BootSizeMB
format fs=fat32 quick label=PARAVIS
active
assign
create partition primary size=32
format fs=fat quick label=VTOYEFI
assign
create partition primary size=$p3MB
format fs=ntfs quick label=DATA
assign
exit
"@
Invoke-Diskpart $dp
Write-Ok "Разделы созданы и отформатированы."
Write-Step "Возврат кода MBR Xorboot (байты 0..445)"
$fs = Open-Physical $diskNum
try {
$fs.Position = 0
$fs.Write($head, 0, 446)
$fs.Flush()
# сектора 1..62 (gap Xorboot) не должны были измениться
$fs.Position = 512
$gap = New-Object byte[] 31744
$n = $fs.Read($gap, 0, $gap.Length)
$gapOk = $true
for ($i = 0; $i -lt $n; $i++) { if ($gap[$i] -ne $head[512 + $i]) { $gapOk = $false; break } }
if (-not $gapOk) {
Write-Warn "Gap-сектора изменились — восстанавливаю сектора 1..62."
$fs.Position = 512
$fs.Write($head, 512, 31744)
$fs.Flush()
} else {
Write-Ok "Gap-сектора (1..62) не тронуты."
}
} finally {
# после записи в сектор 0 Windows инвалидирует хэндл — ошибка Close() не критична
try { $fs.Close() } catch { }
}
Write-Step "Обновление таблицы устройств"
Update-HostStorageCache
Start-Sleep -Seconds 3
$deadline = (Get-Date).AddSeconds(60)
do {
Update-HostStorageCache
$v1 = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$v2 = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$v3 = Get-DiskVolumeLabel $diskNum 'DATA'
if ($v1 -and $v2 -and $v3) { break }
Start-Sleep -Seconds 2
} while ((Get-Date) -lt $deadline)
if (-not ($v1 -and $v2 -and $v3)) { throw "Новые разделы не появились в системе. Проверьте 'Управление дисками'." }
foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) {
Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter
}
Start-Sleep -Seconds 1
Update-HostStorageCache
$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS'
$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI'
$pData = Get-DiskVolumeLabel $diskNum 'DATA'
if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) {
throw "Не всем новым разделам назначены буквы. Откройте «Управление дисками» и назначьте вручную, затем запустите скрипт с -SkipStage."
}
Write-Ok ("новые буквы: PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter)
$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset
$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host
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 "Геометрия разделов корректна."
# --------------------------------------------------------------- 5. 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."
}
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 и маркер на месте."
# ---------------------------------------------------------------- 6. 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)
if ($projSrcSize) {
" проект на p1: {0} файлов, {1:N2} ГБ (источник {2:N2} ГБ)" -f $projDst.Count, ($projDst.Sum/1GB), ($projSrcSize.Sum/1GB)
} else {
" проект на p1: {0} файлов, {1:N2} ГБ" -f $projDst.Count, ($projDst.Sum/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 ($projSrcSize -and $projDst.Sum -ne $projSrcSize.Sum) { Write-Warn "Размер проекта не совпал с источником!" }
Write-Step "Готово"
Write-Host "Дальше:" -ForegroundColor Green
Write-Host " 1. Проверить загрузку Xorboot -> Ventoy."
Write-Host " 2. Если Xorboot не грузится — запустить Change_bootLoader.exe с загрузочного раздела (Install XorBoot)."
Write-Host " 3. Staging можно удалить: $StageDir"
Write-Host (" Бэкап MBR/gap: {0}" -f $mbrFile)
+120
View File
@@ -0,0 +1,120 @@
#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
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
# Build memtest86+ (if needed), sign it, generate menus — everything on D:.
set -e
K=/path/to/pf/Ventoy/keys
D=/path/to/pf/ParavisGrub
A=$D/apps
mkdir -p "$A" "$D/menu"
if [ ! -f /tmp/mt86p/build/x86_64/mt86plus ]; then
echo "=== cloning + building memtest86+"
rm -rf /tmp/mt86p
git clone --depth 1 -q https://github.com/memtest86plus/memtest86plus.git /tmp/mt86p
( cd /tmp/mt86p/build/x86_64 && make -j8 >/tmp/mt86_build.log 2>&1 ) || { tail -20 /tmp/mt86_build.log; exit 1; }
fi
MT=/tmp/mt86p/build/x86_64/mt86plus
echo "=== memtest86+ : $(stat -c %s "$MT") bytes"
cp -f "$MT" "$A/_mt.efi"
sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$A/memtest86p.efi" "$A/_mt.efi" >/dev/null
sbverify --cert "$K/ventoy.crt" "$A/memtest86p.efi" >/dev/null && echo " signed OK"
rm -f "$A/_mt.efi"
ls -l "$A/memtest86p.efi"
echo "=== generating menus"
python3 "$D/gen_menu.py" "$D"
ls -l "$D" "$D/menu"
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
set -e
K=/path/to/pf/Ventoy/keys
D=/path/to/pf/ParavisGrub
A=$D/apps
mkdir -p "$A" "$D/menu"
echo "=== memtest86+ 9.10 -> signed (staged on D:)"
if [ -f /tmp/mt86p/build/x86_64/mt86plus ]; then
cp -f /tmp/mt86p/build/x86_64/mt86plus "$A/mt86plus.raw.efi"
sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$A/memtest86p.efi" "$A/mt86plus.raw.efi"
sbverify --cert "$K/ventoy.crt" "$A/memtest86p.efi"
rm -f "$A/mt86plus.raw.efi"
ls -l "$A/memtest86p.efi"
else
echo " !! build missing in /tmp (wsl restarted?)"
fi
echo "=== generate menu files"
python3 "$D/gen_menu.py" "$D"
ls -l "$D" "$D/menu" "$A"
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
set -e
python3 /path/to/pf/ParavisGrub/build_all.py
echo "=== staged:"
ls -l /path/to/pf/ParavisGrub/theme /path/to/pf/ParavisGrub/theme/main
grep -n 'loadfont\|set theme\|set timeout\|set default' /path/to/pf/ParavisGrub/grub.cfg | head
@@ -0,0 +1,44 @@
# Install the Paravis GRUB2 UEFI loader as the active first/second stage on p1.
# EFI\BOOT\bootx64.efi = shim (MS), EFI\BOOT\fbx64.efi = our signed GRUB2 (+.sbat)
param(
[ValidateSet('grub2','xorboot','ventoy')]
[string]$Loader = 'grub2'
)
$p1 = 'F:'
$boot = "$p1\EFI\BOOT"
$bkp = 'C:\PF\Ventoy\backup\uefi-loaders'
New-Item -ItemType Directory -Force $bkp | Out-Null
function Save-Current([string]$tag) {
Get-ChildItem $boot -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -eq '.efi' } | ForEach-Object {
Copy-Item $_.FullName (Join-Path $bkp "$tag-$($_.Name)") -Force
}
}
Save-Current 'current'
switch ($Loader) {
'grub2' {
Copy-Item 'G:\EFI\BOOT\BOOTX64.EFI' "$boot\bootx64.efi" -Force
Copy-Item 'C:\PF\ParavisGrub\grubx64.efi' "$boot\fbx64.efi" -Force
Copy-Item 'G:\EFI\BOOT\mmx64.efi' "$boot\mmx64.efi" -Force
Copy-Item 'C:\PF\ParavisGrub\grub.cfg' "$p1\efi\Paravis\Boot\grub2\grub.cfg" -Force
}
'xorboot' {
Copy-Item 'C:\PF\Ventoy\backup\xorboot-uefi\bootx64.efi.orig' "$boot\bootx64.efi" -Force
foreach ($f in 'fbx64.efi','mmx64.efi') {
if (Test-Path "$boot\$f") { Remove-Item "$boot\$f" -Force }
}
}
'ventoy' {
# firmware entry should point at p2 (VTOYEFI); nothing to do on p1
Write-Host 'Ventoy is booted directly from p2 (VTOYEFI) - select that entry in firmware'
}
}
Get-ChildItem $boot -File -Filter '*.efi' | Sort-Object Name | ForEach-Object {
$s = Get-AuthenticodeSignature $_.FullName
$subj = if ($s.SignerCertificate) { ($s.SignerCertificate.Subject -replace '^CN=([^,]+).*', '$1') } else { '-' }
"{0,-14} {1,9} {2,-12} {3}" -f $_.Name, $_.Length, $s.Status, $subj
}