Files

272 lines
13 KiB
PowerShell
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Готовит НОВУЮ флешку (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