242 lines
12 KiB
PowerShell
242 lines
12 KiB
PowerShell
#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 "Готово."
|