366 lines
18 KiB
PowerShell
366 lines
18 KiB
PowerShell
#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)
|