Initial source release

This commit is contained in:
Paravis committed 2026-11-13 07:52:38 +03:00
commit 11301fae04
55 files changed
+2652

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
*.exe
*.dll
*.efi
*.signed
*.iso
*.img
*.wim
*.esd
*.pf
*.vhd
*.vmdk
*.bin
*.log
*.tmp
keys/
*.key
*.crt
*.cer
*.pem
*.pfx
*.p12
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Paravis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
# PARAVIS flash build and maintenance scripts
Top-level utilities used to prepare, back up and maintain the PARAVIS flash:
partitioning/backup helpers, BCD operations, grub4dos menu work, XorBoot
deployment, VM helpers and documentation.
## Contents
```
*.ps1, *.cmd backup-flash-*, bcd-*, g4d-*, xor-*, vm-*, font-match.ps1
tools/ diff.py, vector_up2.py
docs/ handoff/history notes, Android bootloader notes, KRD state
```
These are workstation utilities. Absolute paths were replaced with `C:\PF`;
adjust them to your checkout. Disk numbers are examples and must be checked
before running destructive commands.
## Not included
- flash backups (`flash-backup-*`), VHD/VMDK images, logs;
- Secure Boot keys, certificates and signed EFI;
- third-party binaries and bootable images.
## License
MIT.
+75
View File
@@ -0,0 +1,75 @@
# Бэкап первого раздела флешки (F:, метка PARAVIS) — только файлы, без MBR и VBR.
# Куда: C:\PF\flash-backup-2026-10-31\01-PARAVIS-F
# Исключения: System Volume Information, $RECYCLE.BIN — служебные каталоги Windows.
# Скрипт не запустится, если открыта ВМ или целевой каталог уже не пуст.
$ErrorActionPreference = 'Stop'
$src = 'F:\'
$dest = 'C:\PF\flash-backup-2026-10-31\01-PARAVIS-F'
$root = 'C:\PF\flash-backup-2026-10-31'
$log = Join-Path $root '_robocopy-01-PARAVIS-F.log'
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'ВМ запущена — выключите её' }
if (-not (Test-Path $src)) { throw 'Раздел F: не найден' }
if (Test-Path $dest) {
$n = (Get-ChildItem $dest -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object).Count
if ($n -gt 0) { throw "Каталог уже существует и не пуст ($n файлов): $dest" }
} else {
New-Item -ItemType Directory -Force $dest | Out-Null
}
$t0 = Get-Date
# robocopy: /COPY:DAT — файлы с датами, /DCOPY:T — даты каталогов, /XJ — без переходов по связям
$argv = @($src, $dest, '/E', '/R:3', '/W:2', '/NP', '/NFL', '/NDL', '/COPY:DAT', '/DCOPY:T',
'/XD', 'System Volume Information', '$RECYCLE.BIN', '/XJ', ('/LOG+:' + $log))
$out = & robocopy @argv 2>&1
$code = $LASTEXITCODE
if ($code -ge 8) { $out | Select-Object -Last 30; throw "robocopy: код $code" }
"robocopy: код $code (1 = скопированы файлы, это норма)"
# Корень раздела имеет атрибуты Hidden+System — снимаем, иначе папка «пропадёт» из проводника
& attrib.exe -h -s $dest | Out-Null
# --- сверка: сколько файлов и байт на источнике и в бэкапе
$skip = '^\\(System Volume Information|\$RECYCLE\.BIN)(\\|$)'
$sList = Get-ChildItem $src -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { ($_.FullName.Substring(2)) -notmatch $skip }
$dList = Get-ChildItem $dest -Recurse -File -Force -ErrorAction SilentlyContinue
$sSum = ($sList | Measure-Object -Sum Length).Sum
$dSum = ($dList | Measure-Object -Sum Length).Sum
"источник: {0:N0} файлов, {1:N2} ГБ" -f $sList.Count, ($sSum/1GB)
"бэкап: {0:N0} файлов, {1:N2} ГБ" -f $dList.Count, ($dSum/1GB)
if ($sList.Count -ne $dList.Count -or $sSum -ne $dSum) { throw 'РАСХОЖДЕНИЕ: число файлов или байт не совпало' }
# --- контрольные суммы
'--- SHA-256 ...'
$manifest = Join-Path $root 'manifest-01-PARAVIS-F-sha256.txt'
$lines = New-Object System.Collections.Generic.List[string]
Get-ChildItem $dest -Recurse -File -Force | Sort-Object FullName | ForEach-Object {
$rel = $_.FullName.Substring($root.Length + 1)
$lines.Add(('{0} {1,12} {2}' -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash, $_.Length, $rel))
}
$lines | Out-File -Encoding utf8 $manifest
"суммы: $manifest"
# --- описание бэкапа
@(
'Бэкап первого раздела флешки PARAVIS (диск 2, Realtek RTL9210B-CG)',
('Создан: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')),
('Источник: ' + $src + ' (FAT32, метка PARAVIS)'),
'',
'Состав: 01-PARAVIS-F — файлы раздела 1 целиком',
'',
'НЕ входит:',
' * MBR и загрузочный сектор раздела (только файлы)',
' * System Volume Information, $RECYCLE.BIN',
'',
('Файлов: {0:N0}, объём: {1:N2} ГБ' -f $dList.Count, ($dSum/1GB))
) | Out-File -Encoding utf8 (Join-Path $root 'README.txt')
$el = (Get-Date) - $t0
'=== ИТОГО: {0:N0} файлов, {1:N2} ГБ, {2:mm\:ss}' -f $dList.Count, ($dSum/1GB), $el
"каталог: $dest"
+87
View File
@@ -0,0 +1,87 @@
# Бэкап флешки по разделам (без MBR/VBR).
# Исключения: H:\ISO\*.iso, содержимое F:\efi\Paravis\Linux, System Volume Information, $RECYCLE.BIN.
$ErrorActionPreference = 'Stop'
$dest = 'C:\PF\flash-backup-2026-10-30-2'
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — выключите' }
if (Test-Path $dest) {
$n = (Get-ChildItem $dest -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object).Count
if ($n -gt 0) { throw "Каталог $dest уже существует и не пуст ($n файлов)." }
} else {
New-Item -ItemType Directory -Force $dest | Out-Null
}
$common = @('/E','/R:3','/W:2','/NP','/NFL','/NDL','/COPY:DAT','/DCOPY:T',
'/XD','System Volume Information','$RECYCLE.BIN','/XJ')
function Copy-Volume {
param([string]$src,[string]$dstName,[string[]]$extra=@(),[string]$label)
$dst = Join-Path $dest $dstName
New-Item -ItemType Directory -Force $dst | Out-Null
$log = Join-Path $dest ("_robocopy-" + $dstName + ".log")
$argv = @($src,$dst) + $common + $extra + @('/LOG+:' + $log)
"--- $label $src -> $dst"
$out = & robocopy @argv 2>&1
$code = $LASTEXITCODE
if ($code -ge 8) { $out | Select-Object -Last 30; throw "robocopy ${label}: код $code" }
" robocopy код: $code"
$s = Get-ChildItem $dst -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Sum Length
# Корень NTFS-тома имеет атрибуты Hidden+System — robocopy (/COPY:DAT) их копирует. Снимаем.
& attrib.exe -h -s $dst | Out-Null
" скопировано: {0:N0} файлов, {1:N2} ГБ" -f $s.Count,($s.Sum/1GB)
}
$t0 = Get-Date
Copy-Volume 'F:\' '01-PARAVIS-F' @('/XD','F:\efi\Paravis\Linux') 'раздел 1 (F: PARAVIS)'
foreach ($d in 'x64','x86') {
New-Item -ItemType Directory -Force (Join-Path $dest "01-PARAVIS-F\efi\Paravis\Linux\$d") | Out-Null
}
'N:' | Out-File -Encoding utf8 (Join-Path $dest '01-PARAVIS-F\efi\Paravis\Linux\_СОДЕРЖИМОЕ_НЕ_ВХОДИТ_В_БЭКАП.txt')
Copy-Volume 'G:\' '02-VTOYEFI-G' @() 'раздел 2 (G: VTOYEFI)'
Copy-Volume 'H:\' '03-DATA-H' @('/XF','*.iso') 'раздел 3 (H: DATA)'
$readme = @(
'Бэкап флешки PARAVIS FLASH (диск 2) — версия 2, без MBR/VBR',
('Создан: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')),
'',
'Состав:',
' 01-PARAVIS-F — раздел 1, FAT32, метка PARAVIS (F:)',
' 02-VTOYEFI-G — раздел 2, FAT, метка VTOYEFI (G:)',
' 03-DATA-H — раздел 3, NTFS, метка DATA (H:)',
' manifest-sha256.txt — контрольные суммы файлов бэкапа',
'',
'НЕ входит в бэкап:',
' * ISO-файлы в корне H:\ISO',
' * содержимое F:\efi\Paravis\Linux (папка сохранена пустой)',
' * System Volume Information, $RECYCLE.BIN',
' * MBR и загрузочные сектора (в отличие от бэкапа flash-backup-2026-10-30)',
'',
'Состояние на момент бэкапа: KRD 24 (efi\Paravis\KRD\live), Ventoy вместо GFM',
'в меню g4d и bootmgr, KRD 24 в legacy (g4d\antiv), Super GRUB2 с default=detect.'
)
$readme | Out-File -Encoding utf8 (Join-Path $dest 'README.txt')
'--- SHA-256 ...'
$manifest = Join-Path $dest 'manifest-sha256.txt'
$lines = New-Object System.Collections.Generic.List[string]
Get-ChildItem $dest -Recurse -File -Force |
Where-Object { $_.FullName -ne $manifest } |
Sort-Object FullName |
ForEach-Object {
$rel = $_.FullName.Substring($dest.Length + 1)
$h = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$lines.Add(('{0} {1,12} {2}' -f $h, $_.Length, $rel))
}
$lines | Out-File -Encoding utf8 $manifest
$el = (Get-Date) - $t0
$tot = Get-ChildItem $dest -Recurse -File -Force | Measure-Object -Sum Length
''
'=== ИТОГО'
' файлов: {0:N0}' -f $tot.Count
' объём: {0:N2} ГБ' -f ($tot.Sum/1GB)
' время: {0:mm\:ss}' -f $el
' каталог: {0}' -f $dest
+95
View File
@@ -0,0 +1,95 @@
# Часть 1: файловый бэкап флешки по разделам.
# Исключения: ISO-файлы в H:\ISO, содержимое F:\efi\Paravis\Linux,
# служебные System Volume Information / $RECYCLE.BIN.
$ErrorActionPreference = 'Stop'
$dest = 'C:\PF\flash-backup-2026-10-30'
if (Test-Path $dest) {
$n = (Get-ChildItem $dest -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object).Count
if ($n -gt 0) { throw "Каталог $dest уже существует и не пуст ($n файлов). Бэкап не начат." }
} else {
New-Item -ItemType Directory -Force $dest | Out-Null
}
$common = @('/E','/R:2','/W:2','/NP','/NFL','/NDL','/COPY:DAT','/DCOPY:T',
'/XD','System Volume Information','$RECYCLE.BIN','/XJ')
function Copy-Volume {
param([string]$src,[string]$dstName,[string[]]$extra=@(),[string]$label)
$dst = Join-Path $dest $dstName
New-Item -ItemType Directory -Force $dst | Out-Null
$log = Join-Path $dest ("_robocopy-" + $dstName + ".log")
$args_ = @($src,$dst) + $common + $extra + @('/LOG+:' + $log)
"--- $label $src -> $dst"
$out = & robocopy @args_ 2>&1
$code = $LASTEXITCODE
if ($code -ge 8) { $out | Select-Object -Last 30; throw "robocopy ${label}: код $code" }
" robocopy код: $code (0-7 = успех)"
$s = Get-ChildItem $dst -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Sum Length
# Корень NTFS-тома имеет атрибуты Hidden+System — robocopy (/COPY:DAT) их копирует. Снимаем.
& attrib.exe -h -s $dst | Out-Null
" скопировано: {0:N0} файлов, {1:N2} ГБ" -f $s.Count,($s.Sum/1GB)
}
$t0 = Get-Date
# p1 — PARAVIS (F:), без содержимого efi\Paravis\Linux
Copy-Volume 'F:\' '01-PARAVIS-F' @('/XD','F:\efi\Paravis\Linux') 'раздел 1 (F: PARAVIS)'
# пустая структура исключённой папки Linux
foreach ($d in 'x64','x86') {
New-Item -ItemType Directory -Force (Join-Path $dest "01-PARAVIS-F\efi\Paravis\Linux\$d") | Out-Null
}
'N:' | Out-File -Encoding utf8 (Join-Path $dest '01-PARAVIS-F\efi\Paravis\Linux\_СОДЕРЖИМОЕ_НЕ_ВХОДИТ_В_БЭКАП.txt')
# p2 — VTOYEFI (G:)
Copy-Volume 'G:\' '02-VTOYEFI-G' @() 'раздел 2 (G: VTOYEFI)'
# p3 — DATA (H:), без *.iso
Copy-Volume 'H:\' '03-DATA-H' @('/XF','*.iso') 'раздел 3 (H: DATA)'
# Пояснительная записка
$readme = @(
'Бэкап флешки PARAVIS FLASH (диск 2)',
('Создан: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')),
'',
'Состав:',
' 01-PARAVIS-F — раздел 1, FAT32, метка PARAVIS (F:), 14 ГБ',
' 02-VTOYEFI-G — раздел 2, FAT, метка VTOYEFI (G:), 32 МБ',
' 03-DATA-H — раздел 3, NTFS, метка DATA (H:)',
' 00-disk — MBR, таблица разделов и загрузочные сектора (см. backup-flash-sectors.ps1)',
' manifest-sha256.txt — контрольные суммы файлов бэкапа',
'',
'НЕ входит в бэкап (по решению владельца):',
' * ISO-файлы в корне H:\ISO (образы Windows/Linux/Strelec и т.п.)',
' * содержимое F:\efi\Paravis\Linux (образы Linux) — папка сохранена пустой',
' * System Volume Information, $RECYCLE.BIN (служебные)',
'',
'Восстановление файлов: robocopy <папка бэкапа>\01-PARAVIS-F F:\ /E',
'Восстановление загрузочных секторов: см. 00-disk\README.txt'
)
$readme | Out-File -Encoding utf8 (Join-Path $dest 'README.txt')
# Манифест SHA-256
$manifest = Join-Path $dest 'manifest-sha256.txt'
'--- считаю SHA-256 ...'
$lines = New-Object System.Collections.Generic.List[string]
Get-ChildItem $dest -Recurse -File -Force |
Where-Object { $_.FullName -notlike "$dest\manifest-sha256.txt" } |
Sort-Object FullName |
ForEach-Object {
$rel = $_.FullName.Substring($dest.Length + 1)
$h = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$lines.Add(('{0} {1,12} {2}' -f $h, $_.Length, $rel))
}
$lines | Out-File -Encoding utf8 $manifest
$el = (Get-Date) - $t0
$tot = Get-ChildItem $dest -Recurse -File -Force | Measure-Object -Sum Length
''
'=== ИТОГО'
' файлов в бэкапе: {0:N0}' -f $tot.Count
' объём: {0:N2} ГБ' -f ($tot.Sum/1GB)
' время: {0:mm\:ss}' -f $el
' каталог: {0}' -f $dest
' свободно на D: {0:N1} ГБ' -f ((Get-Volume -DriveLetter D).SizeRemaining/1GB)
+80
View File
@@ -0,0 +1,80 @@
# Финальный шаг: README для 00-disk, проверка дампов, пересборка манифеста.
$ErrorActionPreference = 'Stop'
$dest = 'C:\PF\flash-backup-2026-10-30'
$dd = Join-Path $dest '00-disk'
# 1. README для 00-disk
$readme = @(
'Загрузочные области флешки (диск 2), сняты посекторно 2026-10-30.',
'',
'mbr-1MiB.bin — первые 1 048 576 байт диска: MBR, код загрузчика в зазоре,',
' таблица разделов (сигнатура диска 0xAFA17D36, MBR 0x55AA)',
'p1-vbr-1MiB.bin — первый 1 МиБ раздела 1 (F: PARAVIS, FAT32) — VBR/BOOT',
'p2-vbr-1MiB.bin — первый 1 МиБ раздела 2 (G: VTOYEFI, FAT) — VBR/BOOT',
'p3-vbr-1MiB.bin — первый 1 МиБ раздела 3 (H: DATA, NTFS) — VBR/BOOT',
'diskinfo.txt — параметры диска и разделов на момент бэкапа',
'mbr-info.txt — расшифровка таблицы разделов MBR',
'_dump.log — протокол снятия',
'',
'ВОССТАНОВЛЕНИЕ',
' Windows (от администратора), dd из состава Git/gnuwin32:',
' dd if=mbr-1MiB.bin of=\\?\Device\Harddisk2\Partition0 bs=1M count=1',
' dd if=p1-vbr-1MiB.bin of=\\?\Device\Harddisk2\Partition1 bs=1M count=1',
' dd if=p2-vbr-1MiB.bin of=\\?\Device\Harddisk2\Partition2 bs=1M count=1',
' dd if=p3-vbr-1MiB.bin of=\\?\Device\Harddisk2\Partition3 bs=1M count=1',
'',
' Linux:',
' dd if=mbr-1MiB.bin of=/dev/sdX bs=1M count=1 conv=notrunc',
' dd if=p1-vbr-1MiB.bin of=/dev/sdX1 bs=1M count=1 conv=notrunc (и так далее)',
'',
' Или BOOTICE: «Утилиты → Восстановить MBR/PBR из файла».',
'',
'ВАЖНО: в mbr-1MiB.bin лежит и таблица разделов с абсолютными смещениями.',
'Восстанавливать её на флешку с той же разметкой (1 МиБ / 14337 МБ / 14369 МБ).',
'На флешку другого размера переносите только первые 440 байт (код загрузчика),',
'если нужна именно совместимость с имеющейся разметкой.'
)
$readme | Out-File -Encoding utf8 (Join-Path $dd 'README.txt')
# 2. Проверка дампов: сигнатуры
'--- проверка дампов:'
function Sig([string]$file, [int]$n = 8) {
$b = [IO.File]::ReadAllBytes((Join-Path $dd $file))
$head = ($b[0..($n-1)] | ForEach-Object { '{0:X2}' -f $_ }) -join ' '
$txt = -join ($b[3..10] | ForEach-Object { if ($_ -ge 32 -and $_ -lt 127) { [char]$_ } else { '.' } })
' {0,-18} {1} [{2}]' -f $file, $head, $txt
}
Sig 'mbr-1MiB.bin'
Sig 'p1-vbr-1MiB.bin'
Sig 'p2-vbr-1MiB.bin'
Sig 'p3-vbr-1MiB.bin'
$mbr = [IO.File]::ReadAllBytes((Join-Path $dd 'mbr-1MiB.bin'))
' MBR 0x55AA: {0}' -f $(if ($mbr[510] -eq 0x55 -and $mbr[511] -eq 0xAA) { 'есть' } else { 'НЕТ!' })
# 3. Манифест целиком
'--- пересобираю manifest-sha256.txt ...'
$manifest = Join-Path $dest 'manifest-sha256.txt'
$lines = New-Object System.Collections.Generic.List[string]
Get-ChildItem $dest -Recurse -File -Force |
Where-Object { $_.FullName -ne $manifest } |
Sort-Object FullName |
ForEach-Object {
$rel = $_.FullName.Substring($dest.Length + 1)
$h = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$lines.Add(('{0} {1,12} {2}' -f $h, $_.Length, $rel))
}
$lines | Out-File -Encoding utf8 $manifest
# 4. Итог
$tot = Get-ChildItem $dest -Recurse -File -Force | Measure-Object -Sum Length
''
'=== БЭКАП ГОТОВ'
' файлов: {0:N0}' -f $tot.Count
' объём: {0:N2} ГБ' -f ($tot.Sum/1GB)
' каталог: {0}' -f $dest
' строк в манифесте: {0:N0}' -f $lines.Count
foreach ($sub in '01-PARAVIS-F','02-VTOYEFI-G','03-DATA-H','00-disk') {
$m = Get-ChildItem (Join-Path $dest $sub) -Recurse -File -Force | Measure-Object -Sum Length
' {0,-14} {1,6:N0} файлов {2,8:N2} ГБ' -f $sub, $m.Count, ($m.Sum/1GB)
}
' свободно на D: {0:N1} ГБ' -f ((Get-Volume -DriveLetter D).SizeRemaining/1GB)
+80
View File
@@ -0,0 +1,80 @@
# Полный бэкап флешки: все файлы (включая ISO и Linux), без MBR/VBR.
$ErrorActionPreference = 'Stop'
$dest = 'C:\PF\flash-backup-2026-10-30-3'
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — выключите' }
if (Test-Path $dest) {
$n = (Get-ChildItem $dest -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object).Count
if ($n -gt 0) { throw "Каталог $dest уже существует и не пуст ($n файлов)." }
} else {
New-Item -ItemType Directory -Force $dest | Out-Null
}
$common = @('/E','/R:3','/W:3','/NP','/NFL','/NDL','/COPY:DAT','/DCOPY:T',
'/XD','System Volume Information','$RECYCLE.BIN','/XJ')
function Copy-Volume {
param([string]$src,[string]$dstName,[string]$label)
$dst = Join-Path $dest $dstName
New-Item -ItemType Directory -Force $dst | Out-Null
$log = Join-Path $dest ("_robocopy-" + $dstName + ".log")
$argv = @($src,$dst) + $common + @('/LOG+:' + $log)
$t = Get-Date
"--- $label $src -> $dst"
$out = & robocopy @argv 2>&1
$code = $LASTEXITCODE
if ($code -ge 8) { $out | Select-Object -Last 20; throw "robocopy ${label}: код $code" }
$s = Get-ChildItem $dst -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Sum Length
# Корень NTFS-тома имеет атрибуты Hidden+System, и robocopy (/COPY:DAT) их копирует.
# Снимаем сразу, иначе скопированный раздел «пропадает» из обычных списков.
& attrib.exe -h -s $dst | Out-Null
" robocopy код {0}, {1:N0} файлов, {2:N2} ГБ, {3:mm\:ss}" -f $code,$s.Count,($s.Sum/1GB),((Get-Date)-$t)
}
$t0 = Get-Date
Copy-Volume 'F:\' '01-PARAVIS-F' 'раздел 1 (F: PARAVIS)'
Copy-Volume 'G:\' '02-VTOYEFI-G' 'раздел 2 (G: VTOYEFI)'
Copy-Volume 'H:\' '03-DATA-H' 'раздел 3 (H: DATA)'
$readme = @(
'Полный бэкап флешки PARAVIS FLASH (диск 2)',
('Создан: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')),
'',
'Состав:',
' 01-PARAVIS-F — раздел 1, FAT32, метка PARAVIS (F:)',
' 02-VTOYEFI-G — раздел 2, FAT, метка VTOYEFI (G:)',
' 03-DATA-H — раздел 3, NTFS, метка DATA (H:), включая ISO',
' manifest-sha256.txt — контрольные суммы всех файлов',
'',
'Включено всё содержимое разделов (в том числе ISO-образы и efi\Paravis\Linux).',
'НЕ входит:',
' * MBR и загрузочные сектора (VBR) — по решению владельца',
' * System Volume Information, $RECYCLE.BIN (служебные)',
'',
'Состояние: KRD 24 в efi\Paravis\KRD (ia32 без Kaspersky), Ventoy вместо GFM',
'в g4d и bootmgr, Super GRUB2 с default=detect, картинки Xorboot обновлены.'
)
$readme | Out-File -Encoding utf8 (Join-Path $dest 'README.txt')
'--- SHA-256 (может занять пару минут) ...'
$manifest = Join-Path $dest 'manifest-sha256.txt'
$lines = New-Object System.Collections.Generic.List[string]
Get-ChildItem $dest -Recurse -File -Force |
Where-Object { $_.FullName -ne $manifest } |
Sort-Object FullName |
ForEach-Object {
$rel = $_.FullName.Substring($dest.Length + 1)
$h = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$lines.Add(('{0} {1,13} {2}' -f $h, $_.Length, $rel))
}
$lines | Out-File -Encoding utf8 $manifest
$el = (Get-Date) - $t0
$tot = Get-ChildItem $dest -Recurse -File -Force | Measure-Object -Sum Length
''
'=== ИТОГО'
' файлов: {0:N0}' -f $tot.Count
' объём: {0:N2} ГБ' -f ($tot.Sum/1GB)
' время: {0:hh\:mm\:ss}' -f $el
' каталог: {0}' -f $dest
+62
View File
@@ -0,0 +1,62 @@
# Часть 2: дамп загрузочных областей флешки (MBR, таблица разделов, VBR).
# Требует прав администратора (чтение \\.\PhysicalDriveN).
$ErrorActionPreference = 'Stop'
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw 'Нужны права администратора.'
}
$dest = 'C:\PF\flash-backup-2026-10-30\00-disk'
New-Item -ItemType Directory -Force $dest | Out-Null
Start-Transcript -Path (Join-Path $dest '_dump.log') -Force | Out-Null
$diskNo = 2
$dev = '\\.\PhysicalDrive' + $diskNo
$parts = Get-Partition -DiskNumber $diskNo | Sort-Object Offset
$info = @()
$info += 'Диск: PhysicalDrive' + $diskNo
$info += (Get-Disk -Number $diskNo | Format-List * | Out-String)
$info += ''
$info += 'Разделы:'
foreach ($p in $parts) {
$info += (' #{0} {1} offset={2} байт ({3:N0} МБ) размер={4:N0} МБ тип={5} active={6}' -f `
$p.PartitionNumber, $p.DriveLetter, $p.Offset, ($p.Offset/1MB), ($p.Size/1MB), $p.Type, $p.IsActive)
}
$info | Out-File -Encoding utf8 (Join-Path $dest 'diskinfo.txt')
function Dump([string]$file, [long]$offset, [int]$bytes) {
$fs = [IO.File]::Open($dev, 'Open', 'Read', 'ReadWrite')
try {
$fs.Seek($offset, 'Begin') | Out-Null
$buf = New-Object byte[] $bytes
$read = 0
while ($read -lt $bytes) {
$n = $fs.Read($buf, $read, $bytes - $read)
if ($n -le 0) { break }
$read += $n
}
[IO.File]::WriteAllBytes((Join-Path $dest $file), $buf[0..($read-1)])
$h = (Get-FileHash (Join-Path $dest $file) -Algorithm SHA256).Hash
' {0,-18} {1,10:N0} байт sha256={2}' -f $file, $read, $h
} finally { $fs.Close() }
}
'--- дамп загрузочных областей:'
Dump 'mbr-1MiB.bin' 0 (1MB) # MBR + код загрузчика в зазоре
foreach ($p in $parts) {
$name = 'p{0}-vbr-1MiB.bin' -f $p.PartitionNumber
Dump $name $p.Offset (1MB)
}
# расшифровка MBR
$mbr = [IO.File]::ReadAllBytes((Join-Path $dest 'mbr-1MiB.bin'))
$sig = '{0:X2}{1:X2}' -f $mbr[510], $mbr[511]
$diskSig = '{0:X2}{1:X2}{2:X2}{3:X2}' -f $mbr[440],$mbr[441],$mbr[442],$mbr[443]
$tbl = @('MBR подпись: 0x' + $sig, 'Disk signature: 0x' + $diskSig, '',
'Таблица разделов (hex):')
for ($i = 0; $i -lt 4; $i++) {
$o = 446 + $i*16
$tbl += (' #{0}: ' -f ($i+1)) + (($mbr[$o..($o+15)] | ForEach-Object { '{0:X2}' -f $_ }) -join ' ')
}
$tbl | Out-File -Encoding utf8 (Join-Path $dest 'mbr-info.txt')
$tbl
Stop-Transcript | Out-Null
+63
View File
@@ -0,0 +1,63 @@
# Сверка бэкапа v2 с флешкой.
$dest = 'C:\PF\flash-backup-2026-10-30-2'
function Stat($p, $filter) {
$f = Get-ChildItem $p -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\\$RECYCLE\.BIN\\|\\System Volume Information\\' } |
Where-Object { & $filter $_.FullName }
$m = $f | Measure-Object -Sum Length
return [pscustomobject]@{ Count = $m.Count; Sum = $m.Sum }
}
'--- сравнение объёмов:'
$checks = @(
@('F:', 'F:\', "$dest\01-PARAVIS-F", { param($p) $p -notlike 'F:\efi\Paravis\Linux\*' -and $p -ne "$dest\01-PARAVIS-F\efi\Paravis\Linux\_СОДЕРЖИМОЕ_НЕ_ВХОДИТ_В_БЭКАП.txt" }),
@('G:', 'G:\', "$dest\02-VTOYEFI-G", { param($p) $true }),
@('H:', 'H:\', "$dest\03-DATA-H", { param($p) $p -notlike '*.iso' })
)
foreach ($c in $checks) {
$src = Stat $c[1] $c[3]
$dst = Stat $c[2] $c[3]
$ok = ($src.Count -eq $dst.Count -and $src.Sum -eq $dst.Sum)
' {0} источник {1,5} файлов / {2,7:N0} байт бэкап {3,5} / {4,7:N0} {5}' -f `
$c[0], $src.Count, $src.Sum, $dst.Count, $dst.Sum, $(if ($ok) { 'OK' } else { 'РАСХОЖДЕНИЕ' })
}
'--- SHA-256 ключевых файлов:'
$key = @(
'efi\Paravis\Boot\grub2\grub.cfg',
'efi\Paravis\Boot\grub2\menu\utilits.cfg',
'efi\Paravis\Boot\super\x64.efi',
'efi\Paravis\Boot\super\x86.efi',
'efi\Paravis\Boot\super\super.iso',
'efi\Paravis\Boot\g4d\grldr',
'efi\Paravis\Boot\g4d\Ventoy',
'efi\Paravis\Boot\g4d\gfm',
'efi\Paravis\Boot\g4d\antiv',
'efi\Paravis\Boot\xor\xmbr.bin',
'efi\Paravis\Boot\bcd\bcd',
'efi\Paravis\KRD\live\vmlinuz',
'efi\Paravis\KRD\live\initrd.img',
'efi\Paravis\KRD\live\filesystem.squashfs',
'efi\Paravis\KRD\live\KRD\10-krd.srm',
'efi\Paravis\KRD\live\KRD\20-krt.srm',
'efi\Paravis\KRD\live\KRD\30-bases.srm',
'efi\Paravis\Utilities\ADD',
'efi\Paravis\Utilities\ABA',
'Change_bootLoader.exe'
)
$fail = 0
foreach ($k in $key) {
$a = Join-Path 'F:\' $k
$b = Join-Path "$dest\01-PARAVIS-F" $k
if (-not (Test-Path $a)) { ' {0,-52} нет на флешке' -f $k; continue }
if (-not (Test-Path $b)) { ' {0,-52} НЕТ В БЭКАПЕ' -f $k; $fail++; continue }
$h1 = (Get-FileHash $a -Algorithm SHA256).Hash
$h2 = (Get-FileHash $b -Algorithm SHA256).Hash
if ($h1 -ne $h2) { $fail++ }
' {0,-52} {1}' -f $k, $(if ($h1 -eq $h2) { 'OK ' + $h1.Substring(0,12) } else { 'РАСХОЖДЕНИЕ' })
}
''
'--- корень бэкапа:'
Get-ChildItem $dest -Force | Select-Object Mode,Name,Length | Format-Table -AutoSize
if ($fail -eq 0) { '=== ВСЁ СОВПАДАЕТ' } else { "=== РАСХОЖДЕНИЙ: $fail" }
+49
View File
@@ -0,0 +1,49 @@
# Сверка полного бэкапа с флешкой.
$dest = 'C:\PF\flash-backup-2026-10-30-3'
function Stat($p) {
$f = Get-ChildItem $p -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\\$RECYCLE\.BIN\\|\\System Volume Information\\' }
$m = $f | Measure-Object -Sum Length
[pscustomobject]@{ Count = $m.Count; Sum = $m.Sum }
}
'--- объёмы:'
foreach ($v in @(@('F:','F:\', "$dest\01-PARAVIS-F"), @('G:','G:\', "$dest\02-VTOYEFI-G"), @('H:','H:\', "$dest\03-DATA-H"))) {
$a = Stat $v[1]; $b = Stat $v[2]
' {0} источник {1,6:N0} / {2,16:N0} байт бэкап {3,6:N0} / {4,16:N0} {5}' -f `
$v[0], $a.Count, $a.Sum, $b.Count, $b.Sum, $(if ($a.Count -eq $b.Count -and $a.Sum -eq $b.Sum) { 'OK' } else { 'РАСХОЖДЕНИЕ' })
}
'--- SHA-256 ключевых файлов (мелкие):'
$key = @(
'efi\Paravis\Boot\grub2\grub.cfg',
'efi\Paravis\Boot\g4d\grldr',
'efi\Paravis\Boot\xor\xmbr.bin',
'efi\Boot\x86.xor',
'efi\Boot\1x86.bmp',
'efi\Paravis\Boot\bcd\bcd',
'efi\Paravis\KRD\live\KRD\10-krd.srm',
'efi\Paravis\KRD\live\vmlinuz',
'Change_bootLoader.exe'
)
foreach ($k in $key) {
$a = Join-Path 'F:\' $k
$b = Join-Path "$dest\01-PARAVIS-F" $k
if (-not (Test-Path $a)) { ' {0,-46} нет на флешке' -f $k; continue }
if (-not (Test-Path $b)) { ' {0,-46} НЕТ В БЭКАПЕ' -f $k; continue }
$h1 = (Get-FileHash $a -Algorithm SHA256).Hash
$h2 = (Get-FileHash $b -Algorithm SHA256).Hash
' {0,-46} {1}' -f $k, $(if ($h1 -eq $h2) { 'OK ' + $h1.Substring(0,12) } else { 'РАСХОЖДЕНИЕ' })
}
'--- SHA-256 крупных ISO (по одному):'
$isos = Get-ChildItem 'H:\ISO' -File -Filter '*.iso' | Sort-Object Length -Descending
foreach ($iso in ($isos | Select-Object -First 1) + ($isos | Select-Object -Last 1)) {
if (-not $iso) { continue }
$b = Join-Path "$dest\03-DATA-H\ISO" $iso.Name
$t = Get-Date
$h1 = (Get-FileHash $iso.FullName -Algorithm SHA256).Hash
$h2 = (Get-FileHash $b -Algorithm SHA256).Hash
' {0} ({1:N1} ГБ) {2} [{3:mm\:ss}]' -f $iso.Name, ($iso.Length/1GB), $(if ($h1 -eq $h2) { 'OK ' + $h1.Substring(0,12) } else { 'РАСХОЖДЕНИЕ' }), ((Get-Date)-$t)
}
+59
View File
@@ -0,0 +1,59 @@
# Сверка бэкапа с флешкой: имена + размеры, затем SHA-256 по ключевым файлам.
$dest = 'C:\PF\flash-backup-2026-10-30'
function Rel($root, $f) { $f.FullName.Substring($root.Length).TrimStart('\') }
function Compare-Volume {
param($src, $dst, [scriptblock]$filter, [string]$label)
$a = Get-ChildItem $src -Recurse -File -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\\$RECYCLE\.BIN\\|\\System Volume Information\\' } |
Where-Object { & $filter $_.FullName } |
ForEach-Object { [pscustomobject]@{ rel = (Rel $src $_); size = $_.Length } }
$b = Get-ChildItem $dst -Recurse -File -Force -ErrorAction Stop |
Where-Object { $_.Name -ne '_СОДЕРЖИМОЕ_НЕ_ВХОДИТ_В_БЭКАП.txt' } |
ForEach-Object { [pscustomobject]@{ rel = (Rel $dst $_); size = $_.Length } }
$da = $a | Group-Object rel -AsHashTable -AsString
$db = $b | Group-Object rel -AsHashTable -AsString
$missing = @($a | Where-Object { -not $db.ContainsKey($_.rel) })
$extra = @($b | Where-Object { -not $da.ContainsKey($_.rel) })
$differ = @($a | Where-Object { $db.ContainsKey($_.rel) -and $db[$_.rel].size -ne $_.size })
'{0}: источник {1:N0} файлов / {2:N2} ГБ ; бэкап {3:N0} / {4:N2} ГБ' -f `
$label, $a.Count, (($a | Measure-Object -Sum size).Sum/1GB), $b.Count, (($b | Measure-Object -Sum size).Sum/1GB)
' не скопировано: {0} ; лишних: {1} ; размер не совпал: {2}' -f $missing.Count, $extra.Count, $differ.Count
$missing | Select-Object -First 5 | ForEach-Object { ' нет: ' + $_.rel }
$extra | Select-Object -First 5 | ForEach-Object { ' лишний: ' + $_.rel }
$differ | Select-Object -First 5 | ForEach-Object { ' размер: ' + $_.rel }
return ($missing.Count -eq 0 -and $extra.Count -eq 0 -and $differ.Count -eq 0)
}
$ok = $true
$ok = (Compare-Volume 'F:\' "$dest\01-PARAVIS-F" { param($p) $p -notlike 'F:\efi\Paravis\Linux\*' } 'раздел 1 (F:)') -and $ok
$ok = (Compare-Volume 'G:\' "$dest\02-VTOYEFI-G" { param($p) $true } 'раздел 2 (G:)') -and $ok
$ok = (Compare-Volume 'H:\' "$dest\03-DATA-H" { param($p) $p -notlike '*.iso' } 'раздел 3 (H:)') -and $ok
''
'--- SHA-256 ключевых файлов (флешка vs бэкап):'
$key = @(
'efi\Paravis\Boot\grub2\grub.cfg',
'efi\Paravis\Boot\grub2\menu\utilits.cfg',
'efi\Paravis\Boot\super\x64.efi',
'efi\Paravis\Boot\super\x86.efi',
'efi\Paravis\Boot\super\super.iso',
'efi\Paravis\Boot\loaders\grub2\fbx64.efi',
'efi\Paravis\Utilities\ADD',
'efi\Paravis\Utilities\ABA',
'Change_bootLoader.exe',
'EFI\BOOT\bootx64.efi'
)
foreach ($k in $key) {
$p1 = Join-Path 'F:\' $k
$p2 = Join-Path "$dest\01-PARAVIS-F" $k
if (-not (Test-Path $p1)) { ' {0,-46} нет на флешке' -f $k; continue }
if (-not (Test-Path $p2)) { ' {0,-46} НЕТ В БЭКАПЕ' -f $k; $ok = $false; continue }
$h1 = (Get-FileHash $p1 -Algorithm SHA256).Hash
$h2 = (Get-FileHash $p2 -Algorithm SHA256).Hash
' {0,-46} {1}' -f $k, $(if ($h1 -eq $h2) { 'OK ' + $h1.Substring(0,16) } else { 'РАСХОЖДЕНИЕ' })
if ($h1 -ne $h2) { $ok = $false }
}
''
if ($ok) { '=== СВЕРКА: полностью совпадает' } else { '=== СВЕРКА: есть расхождения (см. выше)' }
+39
View File
@@ -0,0 +1,39 @@
# Восстановление центровки в BCD: неразрывные пробелы (U+00A0) перед описаниями.
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$log = 'C:\PF\bcd-center.log'
$gfm = '{212da646-f065-474f-a688-d0ebfefd1573}'
$krd = '{de2ba8ef-1a63-40cd-aeec-56a8efcb0886}'
$nbsp = [string][char]0x00A0
$out = @()
function Run([string[]]$argv) {
$r = & bcdedit @argv 2>&1
$script:out += ('> bcdedit ' + ($argv -join ' '))
$script:out += (' exit=' + $LASTEXITCODE)
if ($r) { $script:out += ($r | ForEach-Object { ' ' + $_ }) }
}
# Kaspersky: 4 NBSP (как было у "...Disk 18"), Ventoy: 7 NBSP
$krdText = ($nbsp * 4) + 'Kaspersky Rescue Disk 24'
$vtText = ($nbsp * 7) + 'Ventoy (ISO образы)'
Run @('/store', $store, '/set', $krd, 'description', $krdText)
Run @('/store', $store, '/set', $gfm, 'description', $vtText)
$out += '=== контроль по байтам BCD:'
$b = [IO.File]::ReadAllBytes($store)
foreach ($pat in 'Kaspersky Rescue Disk 24', 'Ventoy (ISO') {
$needle = [Text.Encoding]::Unicode.GetBytes($pat)
$pos = -1
for ($i = 0; $i -le $b.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($b[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { $pos = $i; break }
}
# считаем U+00A0 (A0 00) непосредственно перед текстом
$n = 0
while ($pos - 2 - $n*2 -ge 0 -and $b[$pos-2-$n*2] -eq 0xA0 -and $b[$pos-1-$n*2] -eq 0x00) { $n++ }
$out += (' {0}: найдено @0x{1:X}, NBSP перед текстом = {2}' -f $pat, $pos, $n)
}
$out | Out-File -FilePath $log -Encoding utf8
+46
View File
@@ -0,0 +1,46 @@
# Центровка описаний в BCD: слева+справа добиваем до 33 символов (U+00A0).
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$log = 'C:\PF\bcd-center2.log'
$gfm = '{212da646-f065-474f-a688-d0ebfefd1573}'
$krd = '{de2ba8ef-1a63-40cd-aeec-56a8efcb0886}'
$nbsp = [string][char]0x00A0
$out = @()
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) {
'VMWARE RUNNING' | Out-File -FilePath $log -Encoding utf8
exit 1
}
function Run([string[]]$argv) {
$r = & bcdedit @argv 2>&1
$script:out += ('> bcdedit ' + ($argv[0..4] -join ' ') + ' ...')
$script:out += (' exit=' + $LASTEXITCODE)
}
$krdText = ($nbsp * 4) + 'Kaspersky Rescue Disk 24' + ($nbsp * 5) # 4 + 24 + 5 = 33
$vtText = ($nbsp * 7) + 'Ventoy (ISO образы)' + ($nbsp * 7) # 7 + 19 + 7 = 33
Run @('/store', $store, '/set', $krd, 'description', $krdText)
Run @('/store', $store, '/set', $gfm, 'description', $vtText)
# контроль
$b = [IO.File]::ReadAllBytes($store)
function Find-Utf16([byte[]]$hay, [string]$s) {
$needle = [Text.Encoding]::Unicode.GetBytes($s)
for ($i = 0; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
foreach ($t in 'Kaspersky Rescue Disk 24','Ventoy (ISO образы)') {
$p = Find-Utf16 $b $t
$lead = 0
while ($p - 2 - $lead*2 -ge 0 -and $b[$p-2-$lead*2] -eq 0xA0 -and $b[$p-1-$lead*2] -eq 0x00) { $lead++ }
$end = $p + [Text.Encoding]::Unicode.GetByteCount($t)
$trail = 0
while ($end + $trail*2 + 1 -lt $b.Length -and $b[$end+$trail*2] -eq 0xA0 -and $b[$end+$trail*2+1] -eq 0x00) { $trail++ }
$out += (' {0}: слева {1}, справа {2}, всего {3}' -f $t, $lead, $trail, ($lead + $t.Length + $trail))
}
$out | Out-File -FilePath $log -Encoding utf8
+12
View File
@@ -0,0 +1,12 @@
# Проверка: как BCD реально отдаёт описания (через bcdedit).
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$log = 'C:\PF\bcd-check.txt'
$gfm = '{212da646-f065-474f-a688-d0ebfefd1573}'
$krd = '{de2ba8ef-1a63-40cd-aeec-56a8efcb0886}'
$out = @()
foreach ($g in $gfm, $krd) {
$r = & bcdedit /store $store /enum $g 2>&1
$out += ('=== ' + $g)
$out += ($r | ForEach-Object { $_ })
}
$out | Out-File -FilePath $log -Encoding utf8
+35
View File
@@ -0,0 +1,35 @@
# Правка BCD флешки: GFM -> Ventoy, и переименование KRD 18 -> 24.
# Требует прав администратора.
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$log = 'C:\PF\bcd-edit.log'
$bak = 'C:\PF\Ventoy\backup\bcd-before-ventoy.bcd'
$out = @()
$out += '=== бэкап'
if (-not (Test-Path $bak)) { Copy-Item $store $bak -Force }
$out += (' ' + $bak + ' : ' + (Test-Path $bak))
$gfm = '{212da646-f065-474f-a688-d0ebfefd1573}'
$krd = '{de2ba8ef-1a63-40cd-aeec-56a8efcb0886}'
function Run([string[]]$argv) {
$r = & bcdedit @argv 2>&1
$script:out += (' > bcdedit ' + ($argv -join ' '))
$script:out += (' exit=' + $LASTEXITCODE)
if ($r) { $script:out += ($r | ForEach-Object { ' ' + $_ }) }
}
$out += '=== Ventoy вместо Grub2 FileManager'
Run @('/store', $store, '/set', $gfm, 'path', '\efi\Paravis\boot\g4d\Ventoy')
Run @('/store', $store, '/set', $gfm, 'description', 'Ventoy (ISO образы)')
$out += '=== KRD 18 -> 24'
Run @('/store', $store, '/set', $krd, 'description', 'Kaspersky Rescue Disk 24')
$out += '=== проверка'
$enum = & bcdedit /store $store /enum $gfm 2>&1
$out += ($enum | ForEach-Object { ' ' + $_ })
$enum2 = & bcdedit /store $store /enum $krd 2>&1
$out += ($enum2 | ForEach-Object { ' ' + $_ })
$out | Out-File -FilePath $log -Encoding utf8
+6
View File
@@ -0,0 +1,6 @@
# Дамп BCD-хранилища флешки (требует прав администратора).
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$log = 'C:\PF\bcd-enum.txt'
$out = & bcdedit /store $store /enum all 2>&1
$out | Out-File -FilePath $log -Encoding utf8
"exit=$LASTEXITCODE" | Out-File -FilePath $log -Encoding utf8 -Append
+41
View File
@@ -0,0 +1,41 @@
# Анализ описаний в BCD: сколько NBSP слева/справа у каждого пункта.
$store = 'F:\efi\Paravis\Boot\bcd\bcd'
$b = [IO.File]::ReadAllBytes($store)
function Find-Utf16([byte[]]$hay, [string]$s) {
$needle = [Text.Encoding]::Unicode.GetBytes($s)
for ($i = 0; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$texts = @(
'Super Grub2',
'Поиск и запуск Windows 7-11',
'Установка Windows 7, 10, 11 x64',
'Установка Windows 7, 10 x86',
'Запуск Windows 7 PE BootPass',
'Ventoy (ISO образы)',
'Kaspersky Rescue Disk 24',
'Перезагрузка',
'Выключение',
'Windows PE Strelec',
'Утилиты для диагностики',
'Windows MSDaRT',
'Установка/Запуск Linux'
)
'текст | слева | справа | всего'
foreach ($t in $texts) {
$p = Find-Utf16 $b $t
if ($p -lt 0) { ' {0} : не найдено' -f $t; continue }
$lead = 0
while ($p - 2 - $lead*2 -ge 0 -and $b[$p-2-$lead*2] -eq 0xA0 -and $b[$p-1-$lead*2] -eq 0x00) { $lead++ }
$end = $p + [Text.Encoding]::Unicode.GetByteCount($t)
$trail = 0
while ($end + $trail*2 + 1 -lt $b.Length -and $b[$end+$trail*2] -eq 0xA0 -and $b[$end+$trail*2+1] -eq 0x00) { $trail++ }
' {0,-36} {1,3} {2,3} {3,4}' -f $t, $lead, $trail, ($lead + $t.Length + $trail)
}
+49
View File
@@ -0,0 +1,49 @@
# Сборка двух маленьких EFI (i386-efi) для ia32 Xorboot:
# ventoy32.efi — находит Ventoy на VTOYEFI и передаёт ему управление
# krd32.efi — грузит KRD 24 (vmlinuz + initrd + live-boot)
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$dir = "$grub\i386-efi"
$out = 'C:\PF\KRD\images'
New-Item -ItemType Directory -Force $out | Out-Null
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux'
$cfgVentoy = @(
'set timeout=0',
'set default=0',
'search --no-floppy --file --set=vtoy /ventoy/vtoyjump32.exe',
'if [ -z "$vtoy" ]; then',
' search --no-floppy --file --set=vtoy /ventoy/ventoy_x86.cpio',
'fi',
'if [ -n "$vtoy" ]; then',
' chainloader ($vtoy)/EFI/BOOT/grubia32.efi',
'else',
' echo "VTOYEFI not found"',
' sleep 5',
'fi'
) -join "`n"
$cfgKrd = @(
'set timeout=0',
'set default=0',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'if [ -z "$krd" ]; then',
' echo "KRD not found"',
' sleep 5',
'else',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
'fi'
) -join "`n"
foreach ($item in @(@('ventoy32.efi', $cfgVentoy), @('krd32.efi', $cfgKrd))) {
$efi = $item[0]; $cfg = $item[1]
$cfgPath = Join-Path $env:TEMP ("$efi.cfg")
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out $efi
if (Test-Path $o) { Remove-Item $o -Force }
& "$grub\grub-mkstandalone.exe" "--directory=$dir" -O i386-efi -o $o `
"--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 6
if (Test-Path $o) { ' OK {0}: {1:N0} байт' -f $efi,(Get-Item $o).Length } else { ' FAIL {0}' -f $efi }
}
+45
View File
@@ -0,0 +1,45 @@
# 64-битные переходники + проверка наличия 32-битной прошивки OVMF в WSL.
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$dir = "$grub\x86_64-efi"
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux'
$cfgVentoy = @(
'set timeout=0',
'set default=0',
'search --no-floppy --file --set=vtoy /ventoy/vtoyjump64.exe',
'if [ -z "$vtoy" ]; then',
' search --no-floppy --file --set=vtoy /ventoy/ventoy.cpio',
'fi',
'if [ -n "$vtoy" ]; then',
' chainloader ($vtoy)/EFI/BOOT/fbx64.efi',
'else',
' echo "VTOYEFI not found"',
' sleep 5',
'fi'
) -join "`n"
$cfgKrd = @(
'set timeout=0',
'set default=0',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'if [ -z "$krd" ]; then',
' echo "KRD not found"',
' sleep 5',
'else',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
'fi'
) -join "`n"
foreach ($item in @(@('ventoy64.efi', $cfgVentoy), @('krd64.efi', $cfgKrd))) {
$efi = $item[0]; $cfg = $item[1]
$cfgPath = Join-Path $env:TEMP ("$efi.cfg")
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out $efi
if (Test-Path $o) { Remove-Item $o -Force }
& "$grub\grub-mkstandalone.exe" "--directory=$dir" -O x86_64-efi -o $o `
"--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 6
if (Test-Path $o) { ' OK {0}: {1:N0} байт' -f $efi,(Get-Item $o).Length } else { ' FAIL {0}' -f $efi }
}
+30
View File
@@ -0,0 +1,30 @@
# Финальные переходники KRD (с командой boot) для ia32 и x64.
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux'
$cfg = @(
'set timeout=0',
'set default=0',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'if [ -z "$krd" ]; then',
' echo "KRD not found"',
' sleep 5',
'else',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
' boot',
'fi'
) -join "`n"
foreach ($arch in @(@('krd32.efi','i386-efi'), @('krd64.efi','x86_64-efi'))) {
$efi = $arch[0]; $platform = $arch[1]
$cfgPath = Join-Path $env:TEMP ("$efi.cfg")
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out $efi
if (Test-Path $o) { Remove-Item $o -Force }
& "$grub\grub-mkstandalone.exe" "--directory=$grub\$platform" -O $platform -o $o `
"--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 5
' {0}: {1:N0} байт' -f $efi,(Get-Item $o).Length
}
+31
View File
@@ -0,0 +1,31 @@
# Переходники KRD с видеомодулями (efi_gop/all_video).
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux all_video efi_gop efi_uga video_bochs video_cirrus font gfxterm'
$cfg = @(
'set timeout=0',
'set default=0',
'insmod all_video',
'set gfxmode=1024x768x32,1024x768,auto',
'set gfxpayload=keep',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'if [ -z "$krd" ]; then',
' echo "KRD not found"',
' sleep 5',
'else',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
' boot',
'fi'
) -join "`n"
foreach ($arch in @(@('krd32.efi','i386-efi'), @('krd64.efi','x86_64-efi'))) {
$efi = $arch[0]; $platform = $arch[1]
$cfgPath = Join-Path $env:TEMP ("$efi.v.cfg")
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out $efi
& "$grub\grub-mkstandalone.exe" "--directory=$grub\$platform" -O $platform -o $o "--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 5
' {0}: {1:N0} байт' -f $efi,(Get-Item $o).Length
}
+28
View File
@@ -0,0 +1,28 @@
# Переходник для KRD 18 (ia32): kernel k-x86 + initrd.xz + subdir.
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux all_video efi_gop efi_uga video_bochs video_cirrus'
$cfg = @(
'set timeout=0',
'set default=0',
'insmod all_video',
'set gfxmode=1024x768x32,1024x768,auto',
'set gfxpayload=keep',
'search --no-floppy --file --set=k18 /efi/Paravis/KRD/k-x86',
'if [ -z "$k18" ]; then',
' echo "KRD18 not found"',
' sleep 5',
'else',
' linux ($k18)/efi/Paravis/KRD/k-x86 net.ifnames=0 lang=ru dostartx subdir=/efi/Paravis/KRD/data',
' initrd ($k18)/efi/Paravis/KRD/initrd.xz',
' boot',
'fi'
) -join "`n"
$cfgPath = Join-Path $env:TEMP 'krd18.cfg'
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out 'krd18.efi'
& "$grub\grub-mkstandalone.exe" "--directory=$grub\i386-efi" -O i386-efi -o $o "--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 5
' krd18.efi: {0:N0} байт' -f (Get-Item $o).Length
+26
View File
@@ -0,0 +1,26 @@
# Вариант KRD-переходника с явным текстовым payload (для 32-битной EFI).
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test linux video'
$cfg = @(
'set timeout=0',
'set default=0',
'set gfxpayload=text',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'if [ -z "$krd" ]; then',
' echo "KRD not found"',
' sleep 5',
'else',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
' boot',
'fi'
) -join "`n"
$cfgPath = Join-Path $env:TEMP 'krd32t.cfg'
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out 'krd32.efi'
& "$grub\grub-mkstandalone.exe" "--directory=$grub\i386-efi" -O i386-efi -o $o "--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 5
' krd32.efi: {0:N0} байт' -f (Get-Item $o).Length
+31
View File
@@ -0,0 +1,31 @@
# Диагностическая сборка krd32.efi: показать результат поиска и список файлов.
$ErrorActionPreference = 'Stop'
$grub = 'C:\PF\grub2-a1ive\grub'
$dir = "$grub\i386-efi"
$out = 'C:\PF\KRD\images'
$mods = 'normal search search_fs_file chain part_msdos part_gpt fat ntfs exfat configfile echo test ls linux'
$cfg = @(
'set timeout=0',
'search --no-floppy --file --set=krd /efi/Paravis/KRD/live/vmlinuz',
'echo "krd=[$krd]"',
'if [ -n "$krd" ]; then',
' echo "--- listing:"',
' ls ($krd)/efi/Paravis/KRD/live',
' echo "--- linux try:"',
' linux ($krd)/efi/Paravis/KRD/live/vmlinuz boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8',
' echo "linux rc=$?"',
' initrd ($krd)/efi/Paravis/KRD/live/initrd.img',
' echo "initrd rc=$?"',
'else',
' echo "KRD NOT FOUND"',
'fi',
'sleep 25'
) -join "`n"
$cfgPath = Join-Path $env:TEMP 'krd32dbg.cfg'
[IO.File]::WriteAllText($cfgPath, $cfg, (New-Object System.Text.UTF8Encoding($false)))
$o = Join-Path $out 'krd32dbg.efi'
if (Test-Path $o) { Remove-Item $o -Force }
& "$grub\grub-mkstandalone.exe" "--directory=$dir" -O i386-efi -o $o "--modules=$mods" "boot/grub/grub.cfg=$cfgPath" 2>&1 | Select-Object -First 5
' OK: {0:N0} байт' -f (Get-Item $o).Length
+38
View File
@@ -0,0 +1,38 @@
# Подбор шрифта по ширине строки "Kaspersky Rescue Disk 18" на Main1.bmp.
Add-Type -AssemblyName System.Drawing
$img = [System.Drawing.Image]::FromFile('F:\efi\Paravis\Boot\xor\Main1.bmp')
$bmp = New-Object System.Drawing.Bitmap $img
# область строки Kaspersky (y 478..505), без хоткея (x до 415)
$minX = 9999; $maxX = -1; $minY = 9999; $maxY = -1
for ($y = 476; $y -le 506; $y++) {
for ($x = 40; $x -le 415; $x++) {
$c = $bmp.GetPixel($x, $y)
if ($c.R + $c.G + $c.B -lt 500) {
if ($x -lt $minX) { $minX = $x }; if ($x -gt $maxX) { $maxX = $x }
if ($y -lt $minY) { $minY = $y }; if ($y -gt $maxY) { $maxY = $y }
}
}
}
"--- текст 'Kaspersky Rescue Disk 18': x {0}..{1} (ширина {2}), y {3}..{4}" -f $minX,$maxX,($maxX-$minX+1),$minY,$maxY
$targetW = $maxX - $minX + 1
$text = 'Kaspersky Rescue Disk 18'
$emSizes = 21.63, 22.0, 21.0, 22.95
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.TextRenderingHint = 'AntiAlias'
$fmt = [System.Drawing.StringFormat]::GenericTypographic
$res = @()
foreach ($fam in [System.Drawing.FontFamily]::Families) {
foreach ($style in @('Regular','Bold')) {
try {
$f = New-Object System.Drawing.Font $fam, 21.63, ([System.Drawing.FontStyle]::$style), ([System.Drawing.GraphicsUnit]::Pixel)
$sz = $g.MeasureString($text, $f, 10000, $fmt)
$res += [pscustomobject]@{ Family = $fam.Name; Style = $style; Width = [math]::Round($sz.Width,1); Diff = [math]::Round([math]::Abs($sz.Width - $targetW),1) }
$f.Dispose()
} catch { }
}
}
$g.Dispose(); $bmp.Dispose(); $img.Dispose()
"--- цель: {0} px" -f $targetW
$res | Sort-Object Diff | Select-Object -First 12 | Format-Table -AutoSize
+18
View File
@@ -0,0 +1,18 @@
# Дамп встроенного меню grldr в текстовый файл для анализа.
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$b = [IO.File]::ReadAllBytes($f)
# ищем BOM в конце файла
$bom = -1
for ($i = $b.Length - 8192; $i -lt $b.Length - 2; $i++) {
if ($b[$i] -eq 0xEF -and $b[$i+1] -eq 0xBB -and $b[$i+2] -eq 0xBF) { $bom = $i; break }
}
"BOM offset: 0x{0:X} ({0}), size={1}, menu bytes={2}" -f $bom, $b.Length, ($b.Length - $bom - 3)
$text = [Text.Encoding]::UTF8.GetString($b[($bom+3)..($b.Length-1)])
$text = $text.TrimEnd([char]0)
$out = 'C:\PF\Ventoy\backup\g4d-grldr-menu.txt'
[IO.File]::WriteAllText($out, $text, (New-Object System.Text.UTF8Encoding($false)))
" сохранено: $out"
" строк: " + ($text -split "`n").Count
+57
View File
@@ -0,0 +1,57 @@
# Исправление: у пункта Ventoy команда от BootPass и наоборот. Правятся оба файла
# (рабочий F:\grldr и шаблон efi\Paravis\Boot\g4d\grldr).
$ErrorActionPreference = 'Stop'
$files = @('F:\grldr', 'F:\efi\Paravis\Boot\g4d\grldr')
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
function LineEnd([byte[]]$hay, [int]$from) {
for ($i = $from; $i -lt $hay.Length; $i++) { if ($hay[$i] -eq 0x0A) { return $i } }
return -1
}
foreach ($f in $files) {
if (-not (Test-Path $f)) { " нет файла $f"; continue }
$b = [IO.File]::ReadAllBytes($f)
$titleV = [Text.Encoding]::UTF8.GetBytes('title' + (' ' * 13) + 'Ventoy (ISO образы)')
$titleB = [Text.Encoding]::UTF8.GetBytes('title' + (' ' * 6) + 'Запуск Windows 7 PE BootPass')
$iV = Find-Bytes $b $titleV
$iB = Find-Bytes $b $titleB
if ($iV -lt 0 -or $iB -lt 0) { " $f : заголовки не найдены (V=$iV B=$iB)"; continue }
if ($iB -lt $iV) { throw "$f : неожиданный порядок пунктов" }
# конец каждого блока = конец строки команды (вторая строка после title)
$vCmdStart = (LineEnd $b $iV) + 1
$vEnd = (LineEnd $b $vCmdStart)
$bCmdStart = (LineEnd $b $iB) + 1
$bEnd = (LineEnd $b $bCmdStart)
if ($vEnd -lt 0 -or $bEnd -lt 0) { throw "$f : не найдены границы" }
$newV = [Text.Encoding]::UTF8.GetBytes("title" + (' ' * 13) + "Ventoy (ISO образы)`nchainloader (bd)/efi/Paravis/boot/g4d/Ventoy")
$newB = [Text.Encoding]::UTF8.GetBytes("title" + (' ' * 6) + "Запуск Windows 7 PE BootPass`nchainloader (bd)/efi/Paravis/Boot/mgr/bootpass")
# заменяем с конца, чтобы не сбить смещения
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($bCmdStart-1)])
$out.AddRange($newB)
$out.AddRange([byte[]]$b[($bEnd)..($iV-1)])
$out.AddRange($newV)
$out.AddRange([byte[]]$b[($vEnd)..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- $f : {0} байт (было {1})" -f $nb.Length, $b.Length
$s = [Text.Encoding]::UTF8.GetString($nb)
$j = $s.IndexOf('Ventoy (ISO')
$ls = $s.LastIndexOf("`n", $j) + 1
$seg = $s.Substring($ls, 220)
($seg -split "`n") | Select-Object -First 4 | ForEach-Object { ' ' + ($_ -replace ' ', '·') }
}
+54
View File
@@ -0,0 +1,54 @@
# Замена пункта Grub2 FileManager на Ventoy в основном меню grub4dos (g4d\grldr).
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$bak = 'C:\PF\Ventoy\backup\g4d-grldr-GFM.bin'
$b = [IO.File]::ReadAllBytes($f)
$text = [Text.Encoding]::UTF8.GetString($b)
$startMarker = 'title Grub2 FileManager'
$start = $text.IndexOf($startMarker)
if ($start -lt 0) { throw 'GFM-блок не найден' }
# конец блока: первый "\nboot\n" после начала
$bootIdx = $text.IndexOf("`nboot`n", $start)
if ($bootIdx -lt 0) { throw 'конец GFM-блока не найден' }
$blockEnd = $bootIdx + ("`nboot`n").Length
$oldBlock = $text.Substring($start, $blockEnd - $start)
"--- старый блок ({0} байт):" -f ([Text.Encoding]::UTF8.GetByteCount($oldBlock))
($oldBlock -split "`n") | ForEach-Object { ' |' + $_ }
$newText = @(
'title Ventoy (ISO образы)',
'map --unmap=0:0x03 > nul',
'map --unhook',
'find --set-root /ventoy/core.img',
'kernel /ventoy/core.img',
'boot'
) -join "`n"
$newText += "`n"
$oldLen = [Text.Encoding]::UTF8.GetByteCount($oldBlock)
$newBytes = [Text.Encoding]::UTF8.GetBytes($newText)
if ($newBytes.Length -gt $oldLen) { throw ("новый блок длиннее: {0} > {1}" -f $newBytes.Length, $oldLen) }
$pad = New-Object byte[] ($oldLen - $newBytes.Length)
for ($i = 0; $i -lt $pad.Length; $i++) { $pad[$i] = 0x20 }
$startByte = [Text.Encoding]::UTF8.GetByteCount($text.Substring(0, $start))
$endByte = $startByte + $oldLen
if (-not (Test-Path $bak)) { Copy-Item $f $bak -Force; ' бэкап: ' + $bak }
Set-ItemProperty -Path $f -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($startByte-1)])
$out.AddRange($newBytes); $out.AddRange($pad)
$out.AddRange([byte[]]$b[$endByte..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
"--- размер: {0} (было {1})" -f (Get-Item $f).Length, $b.Length
$chk = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($f))
$i2 = $chk.IndexOf('title Ventoy')
"--- новый блок:"
$chk.Substring($i2, 180) -split "`n" | Select-Object -First 7 | ForEach-Object { ' |' + $_ }
"--- остались ссылки: GFM={0}, gfm.iso={1}" -f ([regex]::Matches($chk,'Grub2 FileManager').Count), ([regex]::Matches($chk,'gfm\.iso').Count)
+55
View File
@@ -0,0 +1,55 @@
# Восстановление grldr из бэкапа + корректная замена GFM -> Ventoy (поиск по байтам).
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$bak = 'C:\PF\Ventoy\backup\g4d-grldr-GFM.bin'
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
$limit = $hay.Length - $needle.Length
for ($i = $from; $i -le $limit; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
# 1. восстановление
Copy-Item $bak $f -Force
Set-ItemProperty -Path $f -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue
$b = [IO.File]::ReadAllBytes($f)
"--- восстановлен: {0} байт" -f $b.Length
# 2. поиск блока
$startMarker = [Text.Encoding]::ASCII.GetBytes('title Grub2 FileManager')
$start = Find-Bytes $b $startMarker
if ($start -lt 0) { throw 'GFM-блок не найден' }
$bootMarker = [Text.Encoding]::ASCII.GetBytes("`nboot`n")
$bootPos = Find-Bytes $b $bootMarker $start
if ($bootPos -lt 0) { throw 'конец блока не найден' }
$blockEnd = $bootPos + $bootMarker.Length
$oldLen = $blockEnd - $start
"--- блок найден: 0x{0:X}, длина {1} байт" -f $start, $oldLen
$newText = (@(
'title Ventoy (ISO образы)',
'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
) -join "`n") + "`n"
$newBytes = [Text.Encoding]::UTF8.GetBytes($newText)
"--- новый блок: {0} байт" -f $newBytes.Length
if ($newBytes.Length -gt $oldLen) { throw "новый блок длиннее ($($newBytes.Length) > $oldLen)" }
$pad = New-Object byte[] ($oldLen - $newBytes.Length)
for ($i = 0; $i -lt $pad.Length; $i++) { $pad[$i] = 0x20 }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($newBytes)
$out.AddRange($pad)
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- итог: {0} байт (было {1}, дельта {2})" -f $nb.Length, $b.Length, ($nb.Length - $b.Length)
"--- префикс до блока совпадает: " + $((0..($start-1) | ForEach-Object { $nb[$_] -ne $b[$_] } | Where-Object { $_ } | Measure-Object).Count -eq 0)
$t = [Text.Encoding]::UTF8.GetString($nb[$start..($blockEnd-1)])
($t -split "`n") | ForEach-Object { ' |' + $_ }
"--- GFM-ссылок осталось: " + ([regex]::Matches([Text.Encoding]::UTF8.GetString($nb),'Grub2 FileManager').Count)
+46
View File
@@ -0,0 +1,46 @@
# Замена блока KRD в основном меню grub4dos (g4d\grldr), длина блока сохраняется.
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$bak = 'C:\PF\Ventoy\backup\g4d-grldr-KRD18.bin'
$b = [IO.File]::ReadAllBytes($f)
$s = [Text.Encoding]::ASCII.GetString($b)
$start = $s.IndexOf('title Kaspersky Rescue Disk 18')
if ($start -lt 0) { throw 'KRD-блок не найден' }
$endMarker = "initrd`t%path%/initrd.xz`n"
$endPos = $s.IndexOf($endMarker, $start)
if ($endPos -lt 0) { throw 'конец KRD-блока не найден' }
$blockLen = ($endPos + $endMarker.Length) - $start
$lines = @(
'title Kaspersky Rescue Disk 24',
'set path=/efi/Paravis/KRD',
'set lang=ru',
'find --set-root %path%/live/vmlinuz',
"kernel`t%path%/live/vmlinuz boot=live components live-media-path=%path%/live locales=ru_RU.UTF-8",
"initrd`t%path%/live/initrd.img"
)
$new = ($lines -join "`n") + "`n"
if ($new.Length -gt $blockLen) { throw ("Новый блок длиннее старого: {0} > {1}" -f $new.Length, $blockLen) }
$new = $new + (' ' * ($blockLen - $new.Length))
if ($new.Length -ne $blockLen) { throw 'Ошибка выравнивания длины' }
if (-not (Test-Path $bak)) { Copy-Item $f $bak -Force; ' бэкап: ' + $bak }
Set-ItemProperty -Path $f -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange([Text.Encoding]::ASCII.GetBytes($new))
$out.AddRange([byte[]]$b[($start+$blockLen)..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- размер: {0} (было {1}), дельта {2}" -f $nb.Length, $b.Length, ($nb.Length - $b.Length)
"--- блок KRD теперь:"
$ns = [Text.Encoding]::ASCII.GetString($nb[$start..($start+$blockLen-1)])
($ns -split "`n") | ForEach-Object { ' |' + $_ }
"--- остались ли ссылки на старый KRD:"
$all = [Text.Encoding]::ASCII.GetString($nb)
" k-x86: {0}, initrd.xz: {1}, Disk 18: {2}" -f ([regex]::Matches($all,'k-x86').Count), ([regex]::Matches($all,'initrd\.xz').Count), ([regex]::Matches($all,'Disk 18').Count)
"--- хвост (шрифт) на месте: {0}" -f $(if ($nb[$nb.Length-1] -eq $b[$b.Length-1]) { 'да' } else { 'ПРОВЕРИТЬ' })
+19
View File
@@ -0,0 +1,19 @@
# Анализ структуры меню grldr: где кончается текст и что идёт дальше.
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$b = [IO.File]::ReadAllBytes($f)
$s = [Text.Encoding]::ASCII.GetString($b)
$i = $s.IndexOf('title Kaspersky Rescue Disk 18')
"KRD-блок начинается: 0x{0:X}" -f $i
$endMarker = "initrd`t%path%/initrd.xz`n"
$j = $s.IndexOf($endMarker, $i)
"initrd-строка: 0x{0:X}, длина маркера {1}" -f $j, $endMarker.Length
$blockEnd = $j + $endMarker.Length
"конец блока: 0x{0:X}, длина блока: {1} байт" -f $blockEnd, ($blockEnd - $i)
"--- байты после блока (32):"
(($b[$blockEnd..($blockEnd+31)] | ForEach-Object { '{0:X2}' -f $_ }) -join ' ')
"--- позиция первого 0x00 после блока:"
$z = -1
for ($k = $blockEnd; $k -lt $blockEnd + 4096; $k++) { if ($b[$k] -eq 0) { $z = $k; break } }
" 0x{0:X} (смещение от конца блока: {1})" -f $z, ($z - $blockEnd)
+73
View File
@@ -0,0 +1,73 @@
# Полная пересборка меню g4d из чистого бэкапа: KRD 24 + Ventoy (13 пробелов).
# Результат пишется в рабочий F:\grldr и в шаблон efi\Paravis\Boot\g4d\grldr.
$ErrorActionPreference = 'Stop'
$base = 'C:\PF\Ventoy\backup\g4d-grldr-KRD18.bin'
$targets = @('F:\grldr', 'F:\efi\Paravis\Boot\g4d\grldr')
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
function Replace-Block([byte[]]$data, [byte[]]$startNeedle, [byte[]]$endNeedle, [string]$newText) {
$s = Find-Bytes $data $startNeedle
if ($s -lt 0) { throw 'начало блока не найдено' }
$e = Find-Bytes $data $endNeedle $s
if ($e -lt 0) { throw 'конец блока не найден' }
$endPos = $e + $endNeedle.Length
$oldLen = $endPos - $s
$nb = [Text.Encoding]::UTF8.GetBytes($newText)
if ($nb.Length -gt $oldLen) { throw ("блок не влезает: {0} > {1}" -f $nb.Length, $oldLen) }
$pad = New-Object byte[] ($oldLen - $nb.Length)
for ($i = 0; $i -lt $pad.Length; $i++) { $pad[$i] = 0x20 }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$data[0..($s-1)])
$out.AddRange($nb); $out.AddRange($pad)
$out.AddRange([byte[]]$data[$endPos..($data.Length-1)])
return ,$out.ToArray()
}
$b = [IO.File]::ReadAllBytes($base)
"--- база: {0} байт" -f $b.Length
# 1) KRD 18 -> 24
$krdNew = "title" + (' ' * 10) + "Kaspersky Rescue Disk 24`n" +
"set path=/efi/Paravis/KRD`n" +
"set lang=ru`n" +
"find --set-root %path%/live/vmlinuz`n" +
"kernel`t%path%/live/vmlinuz boot=live components live-media-path=%path%/live locales=ru_RU.UTF-8`n" +
"initrd`t%path%/live/initrd.img`n"
$b = Replace-Block $b ([Text.Encoding]::UTF8.GetBytes('title Kaspersky Rescue Disk 18')) ([Text.Encoding]::UTF8.GetBytes("initrd`t%path%/initrd.xz`n")) $krdNew
"--- после KRD: {0} байт" -f $b.Length
# 2) Grub2 FileManager -> Ventoy
$vtNew = "title" + (' ' * 13) + "Ventoy (ISO образы)`n" +
"chainloader (bd)/efi/Paravis/boot/g4d/Ventoy`n"
$b = Replace-Block $b ([Text.Encoding]::UTF8.GetBytes('title Grub2 FileManager')) ([Text.Encoding]::UTF8.GetBytes("`nboot`n")) $vtNew
"--- после Ventoy: {0} байт" -f $b.Length
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — отмена' }
foreach ($t in $targets) {
[IO.File]::WriteAllBytes($t, $b)
"--- записан: {0} ({1} байт)" -f $t, (Get-Item $t).Length
}
# 3) проверка пар "title -> команда"
$s = [Text.Encoding]::UTF8.GetString($b)
$lines = $s -split "`n"
$res = @()
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match '^title\s*(.*)$') {
$ttl = $Matches[1].Trim()
$cmd = ''
for ($k = $i + 1; $k -lt [Math]::Min($i + 4, $lines.Count); $k++) {
if ($lines[$k] -match '^\s*(chainloader|kernel|map|halt|reboot|set|configfile|find)') { $cmd = $lines[$k].Trim(); break }
}
$res += (' {0,-42} -> {1}' -f $ttl, $cmd)
}
}
'--- итоговое меню:'
$res | Select-Object -First 20
+15
View File
@@ -0,0 +1,15 @@
# Синхронизация g4d-меню: шаблон -> рабочий файл в корне раздела.
# Использование: powershell -File C:\PF\g4d-sync.ps1
$ErrorActionPreference = 'Stop'
$template = 'F:\efi\Paravis\Boot\g4d\grldr'
$working = 'F:\grldr'
if (-not (Test-Path $template)) { throw "нет шаблона: $template" }
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — сначала выключите' }
Copy-Item $template $working -Force
$h1 = (Get-FileHash $template -Algorithm SHA256).Hash
$h2 = (Get-FileHash $working -Algorithm SHA256).Hash
' шаблон: {0:N0} байт {1}' -f (Get-Item $template).Length, $h1.Substring(0,16)
' корень: {0:N0} байт {1}' -f (Get-Item $working).Length, $h2.Substring(0,16)
' {0}' -f $(if ($h1 -eq $h2) { 'OK: синхронизировано' } else { 'РАСХОЖДЕНИЕ' })
+58
View File
@@ -0,0 +1,58 @@
# Ventoy в g4d: 20 пробелов перед пунктом, длина файла сохраняется.
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$origSize = 325669
$spaces = 20
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена' }
$b = [IO.File]::ReadAllBytes($f)
"--- файл до правки: {0} байт" -f $b.Length
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title'))
while ($start -ge 0) {
$chunk = [Text.Encoding]::UTF8.GetString($b[$start..([Math]::Min($b.Length-1, $start+60))])
if ($chunk -match '^title\s+Ventoy \(ISO') { break }
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title')) ($start + 5)
}
if ($start -lt 0) { throw 'Ventoy не найден' }
$nextTitle = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`ntitle")) $start
if ($nextTitle -lt 0) { throw 'следующий title не найден' }
$blockEnd = $nextTitle + 1
$oldLen = $blockEnd - $start
$curLineEnd = (Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`n")) $start)
$curLine = [Text.Encoding]::UTF8.GetString($b[$start..($curLineEnd-1)])
"--- сейчас: '{0}'" -f ($curLine -replace ' ','·')
$line1 = 'title' + (' ' * $spaces) + 'Ventoy (ISO образы)'
$line2 = 'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
$coreLen = [Text.Encoding]::UTF8.GetByteCount($line1) + 1 + [Text.Encoding]::UTF8.GetByteCount($line2) + 1
if ($coreLen -gt $oldLen) { throw ("не влезает: {0} > {1}" -f $coreLen, $oldLen) }
$newBytes = New-Object System.Collections.Generic.List[byte]
$newBytes.AddRange([Text.Encoding]::UTF8.GetBytes($line1)); $newBytes.Add(0x0A)
$newBytes.AddRange([Text.Encoding]::UTF8.GetBytes($line2))
for ($i = 0; $i -lt ($oldLen - $coreLen); $i++) { $newBytes.Add(0x20) }
$newBytes.Add(0x0A)
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($newBytes.ToArray())
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- файл после: {0} байт (эталон {1}) {2}" -f $nb.Length, $origSize, $(if ($nb.Length -eq $origSize) { 'OK' } else { 'РАЗМЕР ИЗМЕНИЛСЯ' })
$ns = [Text.Encoding]::UTF8.GetString($nb[$start..($start+$oldLen-1)])
($ns -split "`n") | ForEach-Object { ' |' + (($_ -replace ' ','·').Substring(0,[Math]::Min(70,$_.Length))) }
+51
View File
@@ -0,0 +1,51 @@
# Инлайн команд Ventoy в меню g4d (вместо chainloader на g4d\Ventoy).
$ErrorActionPreference = 'Stop'
$targets = @('F:\grldr', 'F:\efi\Paravis\Boot\g4d\grldr')
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — отмена' }
$line1 = 'title' + (' ' * 13) + 'Ventoy (ISO образы)'
$line2 = 'find --set-root /ventoy/core.img'
$line3 = 'kernel /ventoy/core.img'
$line4 = 'boot'
foreach ($f in $targets) {
$b = [IO.File]::ReadAllBytes($f)
$startNeedle = [Text.Encoding]::UTF8.GetBytes('title' + (' ' * 13) + 'Ventoy (ISO')
$start = Find-Bytes $b $startNeedle
if ($start -lt 0) { " $f : пункт Ventoy не найден"; continue }
$nextTitle = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`ntitle")) $start
if ($nextTitle -lt 0) { throw "$f : следующий title не найден" }
$blockEnd = $nextTitle + 1
$oldLen = $blockEnd - $start
$core = [Text.Encoding]::UTF8.GetBytes($line1 + "`n" + $line2 + "`n" + $line3 + "`n" + $line4 + "`n")
if ($core.Length -gt $oldLen) { throw ("$f : не влезает {0} > {1}" -f $core.Length, $oldLen) }
# добивка — в конец строки boot (перед завершающим \n), чтобы не было «строки из пробелов»
$body = New-Object System.Collections.Generic.List[byte]
$body.AddRange([byte[]]$core[0..($core.Length-2)])
for ($i = 0; $i -lt ($oldLen - $core.Length); $i++) { $body.Add(0x20) }
$body.Add(0x0A)
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($body.ToArray())
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- $f : {0} байт (было {1})" -f $nb.Length, $b.Length
$t = [Text.Encoding]::UTF8.GetString($nb[$start..($start+$oldLen-1)])
($t -split "`n") | ForEach-Object { ' ' + (($_ -replace ' ','·').Substring(0,[Math]::Min(60,$_.Length))) }
}
+44
View File
@@ -0,0 +1,44 @@
# Пересборка пункта Ventoy в g4d: без ведущих пробелов, добивка в конце строки chainloader.
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$b = [IO.File]::ReadAllBytes($f)
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title Ventoy (ISO'))
if ($start -lt 0) { throw 'пункт Ventoy не найден' }
$bootPos = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`nboot`n")) $start
if ($bootPos -lt 0) { throw 'конец блока не найден' }
$blockEnd = $bootPos + 6
$oldLen = $blockEnd - $start
$line1 = 'title' + (' ' * 13) + 'Ventoy (ISO образы)'
$line2 = 'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
$base = ($line1 + "`n" + $line2).Length + 1 # + завершающий \n
"--- старый блок {0} байт, база {1} байт, добивка {2}" -f $oldLen, $base, ($oldLen - $base)
if ($base -gt $oldLen) { throw 'не влезает' }
$newText = $line1 + "`n" + $line2 + (' ' * ($oldLen - $base)) + "`n"
$newBytes = [Text.Encoding]::UTF8.GetBytes($newText)
"--- итоговая длина блока: {0}" -f $newBytes.Length
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — отмена' }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($newBytes)
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- файл: {0} байт (было {1})" -f $nb.Length, $b.Length
$txt = [Text.Encoding]::UTF8.GetString($nb[$start..($start+80)])
'--- начало блока:'
$txt -split "`n" | Select-Object -First 3 | ForEach-Object { ' |' + (($_ -replace ' ','·').Substring(0,[Math]::Min(80,$_.Length))) }
+46
View File
@@ -0,0 +1,46 @@
# Пересборка пункта Ventoy в g4d: 13 пробелов, граница — следующий "title".
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$b = [IO.File]::ReadAllBytes($f)
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title Ventoy (ISO'))
if ($start -lt 0) { throw 'пункт Ventoy не найден' }
$nextTitle = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`ntitle")) $start
if ($nextTitle -lt 0) { throw 'следующий title не найден' }
$blockEnd = $nextTitle + 1
$oldLen = $blockEnd - $start
'--- текущий блок ({0} байт):' -f $oldLen
$cur = [Text.Encoding]::UTF8.GetString($b[$start..($blockEnd-1)])
($cur -split "`n") | ForEach-Object { ' |' + ($_ -replace ' ','·') }
$line1 = 'title' + (' ' * 13) + 'Ventoy (ISO образы)'
$line2 = 'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
$base = $line1.Length + 1 + $line2.Length + 1
if ($base -gt $oldLen) { throw ("не влезает: база {0} > {1}" -f $base, $oldLen) }
$newText = $line1 + "`n" + $line2 + (' ' * ($oldLen - $base)) + "`n"
$newBytes = [Text.Encoding]::UTF8.GetBytes($newText)
"--- новый блок: {0} байт (нужно {1})" -f $newBytes.Length, $oldLen
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — отмена' }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($newBytes)
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- файл: {0} байт (было {1})" -f $nb.Length, $b.Length
'--- новый блок:'
$t = [Text.Encoding]::UTF8.GetString($nb[$start..($start+$oldLen-1)])
($t -split "`n") | ForEach-Object { ' |' + ($_ -replace ' ','·') }
+56
View File
@@ -0,0 +1,56 @@
# Точная подгонка блока Ventoy по байтам: вернуть размер файла 325669.
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$origSize = 325669
$b = [IO.File]::ReadAllBytes($f)
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title'))
while ($start -ge 0) {
$chunk = [Text.Encoding]::UTF8.GetString($b[$start..([Math]::Min($b.Length-1, $start+40))])
if ($chunk -match '^title\s+Ventoy \(ISO') { break }
$start = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes('title')) ($start + 5)
}
if ($start -lt 0) { throw 'Ventoy-блок не найден' }
$nextTitle = Find-Bytes $b ([Text.Encoding]::ASCII.GetBytes("`ntitle")) $start
if ($nextTitle -lt 0) { throw 'следующий title не найден' }
$blockEnd = $nextTitle + 1
$needShrink = $b.Length - $origSize
"--- файл сейчас {0} байт, нужно вернуть {1} (убрать {2})" -f $b.Length, $origSize, $needShrink
$line1 = 'title' + (' ' * 13) + 'Ventoy (ISO образы)'
$line2 = 'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
$core = [Text.Encoding]::UTF8.GetBytes($line1 + "`n" + $line2 + "`n")
$target = ($blockEnd - $start) - $needShrink
if ($core.Length -gt $target) { throw ("не влезает: {0} > {1}" -f $core.Length, $target) }
$pad = New-Object byte[] ($target - $core.Length)
for ($i = 0; $i -lt $pad.Length; $i++) { $pad[$i] = 0x20 }
# добивка ставится в конец строки chainloader (перед последним \n)
$body = New-Object System.Collections.Generic.List[byte]
$body.AddRange([byte[]]$core[0..($core.Length-2)])
$body.AddRange($pad)
$body.Add(0x0A)
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — отмена' }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($body.ToArray())
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- файл: {0} байт (цель {1}) {2}" -f $nb.Length, $origSize, $(if ($nb.Length -eq $origSize) { 'OK' } else { 'ПРОВЕРИТЬ' })
'--- блок:'
$t = [Text.Encoding]::UTF8.GetString($nb[$start..($start + $target - 1)])
($t -split "`n") | ForEach-Object { ' |' + (($_ -replace ' ','·').Substring(0,[Math]::Min(60,$_.Length))) }
+45
View File
@@ -0,0 +1,45 @@
# Сдвиг пункта Ventoy в g4d: 13 ведущих пробелов вместо 5 (длина файла сохраняется).
$ErrorActionPreference = 'Stop'
$f = 'F:\efi\Paravis\Boot\g4d\grldr'
$b = [IO.File]::ReadAllBytes($f)
function Find-Bytes([byte[]]$hay, [byte[]]$needle, [int]$from = 0) {
for ($i = $from; $i -le $hay.Length - $needle.Length; $i++) {
$ok = $true
for ($j = 0; $j -lt $needle.Length; $j++) { if ($hay[$i+$j] -ne $needle[$j]) { $ok = $false; break } }
if ($ok) { return $i }
}
return -1
}
$startMarker = [Text.Encoding]::ASCII.GetBytes('title Ventoy (ISO')
$start = Find-Bytes $b $startMarker
if ($start -lt 0) { throw 'пункт Ventoy не найден' }
$bootMarker = [Text.Encoding]::ASCII.GetBytes("`nboot`n")
$bootPos = Find-Bytes $b $bootMarker $start
if ($bootPos -lt 0) { throw 'конец блока не найден' }
$blockEnd = $bootPos + $bootMarker.Length
$oldLen = $blockEnd - $start
$newText = (@(
('title' + (' ' * 13) + 'Ventoy (ISO образы)'),
'chainloader (bd)/efi/Paravis/boot/g4d/Ventoy'
) -join "`n") + "`n"
$newBytes = [Text.Encoding]::UTF8.GetBytes($newText)
"--- старый блок {0} байт, новый {1} байт" -f $oldLen, $newBytes.Length
if ($newBytes.Length -gt $oldLen) { throw 'не влезает' }
$pad = New-Object byte[] ($oldLen - $newBytes.Length)
for ($i = 0; $i -lt $pad.Length; $i++) { $pad[$i] = 0x20 }
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange([byte[]]$b[0..($start-1)])
$out.AddRange($newBytes); $out.AddRange($pad)
$out.AddRange([byte[]]$b[$blockEnd..($b.Length-1)])
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — правка отменена' }
[IO.File]::WriteAllBytes($f, $out.ToArray())
$nb = [IO.File]::ReadAllBytes($f)
"--- итог: {0} байт (было {1})" -f $nb.Length, $b.Length
$t = [Text.Encoding]::UTF8.GetString($nb[$start..($blockEnd-1)])
($t -split "`n") | ForEach-Object { ' |' + ($_ -replace ' ', '·') }
+24
View File
@@ -0,0 +1,24 @@
# Заливка KRD 24 на флешку: удаление старого KRD 18 и копирование файлов.
$ErrorActionPreference = 'Stop'
$src = 'C:\PF\KRD\files'
$dst = 'F:\efi\Paravis\KRD'
$bak = 'C:\PF\KRD\old-KRD18'
if (Test-Path $dst) {
Remove-Item $dst -Recurse -Force
' старый KRD 18 удалён с флешки (копия: flash-backup-2026-10-30\01-PARAVIS-F\efi\Paravis\KRD)'
}
New-Item -ItemType Directory -Force $dst | Out-Null
robocopy $src $dst /E /R:2 /W:2 /NFL /NDL /NJH /NJS /NP | Out-Null
if ($LASTEXITCODE -ge 8) { throw "robocopy: $LASTEXITCODE" }
'--- на флешке:'
Get-ChildItem $dst -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Substring($dst.Length+1)}},@{n='MB';e={[math]::Round($_.Length/1MB,2)}} | Format-Table -AutoSize
'--- сверка размеров источник/флешка:'
$s1 = Get-ChildItem $src -Recurse -File | Measure-Object -Sum Length
$s2 = Get-ChildItem $dst -Recurse -File | Measure-Object -Sum Length
' источник: {0} файлов, {1:N0} байт' -f $s1.Count,$s1.Sum
' флешка: {0} файлов, {1:N0} байт' -f $s2.Count,$s2.Sum
if ($s1.Count -eq $s2.Count -and $s1.Sum -eq $s2.Sum) { ' OK: совпадает' } else { ' РАСХОЖДЕНИЕ' }
'--- свободно на F: {0:N0} МБ' -f ((Get-Volume -DriveLetter F).SizeRemaining/1MB)
+45
View File
@@ -0,0 +1,45 @@
# Обновление legacy-пункта KRD в grub4dos (g4d\antiv) на KRD 24.
$ErrorActionPreference = 'Stop'
$src = 'F:\efi\Paravis\Boot\g4d\antiv'
$bak = 'C:\PF\Ventoy\backup\g4d-antiv-KRD18.bin'
$off = 0x4EAB8 # смещение BOM (меню начинается сразу за ним)
$b = [IO.File]::ReadAllBytes($src)
if ($b[$off] -ne 0xEF -or $b[$off+1] -ne 0xBB -or $b[$off+2] -ne 0xBF) {
throw ("Не найден BOM меню по смещению 0x{0:X}" -f $off)
}
$menu = @(
'debug off',
'timeout 0',
'set path=/efi/Paravis/KRD',
'set lang=ru',
'find --set-root %path%/live/vmlinuz',
'kernel %path%/live/vmlinuz boot=live components live-media-path=%path%/live locales=ru_RU.UTF-8',
'initrd %path%/live/initrd.img'
) -join "`n"
$menuBytes = [Text.Encoding]::ASCII.GetBytes($menu + "`n" + [char]0)
$head = New-Object byte[] $off
[Array]::Copy($b, $head, $off)
$out = New-Object System.Collections.Generic.List[byte]
$out.AddRange($head)
$out.Add(0xEF); $out.Add(0xBB); $out.Add(0xBF)
$out.AddRange($menuBytes)
New-Item -ItemType Directory -Force (Split-Path $bak) | Out-Null
if (-not (Test-Path $bak)) { Copy-Item $src $bak -Force; ' старое меню сохранено: ' + $bak }
Set-ItemProperty -Path $src -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue
[IO.File]::WriteAllBytes($src, $out.ToArray())
'--- новый файл: {0:N0} байт (было {1:N0})' -f (Get-Item $src).Length, $b.Length
'--- префикс до меню совпадает с оригиналом: ' + $(if ((Get-FileHash $src -Algorithm SHA256).Hash) { 'проверяю...' })
$nb = [IO.File]::ReadAllBytes($src)
$same = $true
for ($i = 0; $i -lt $off; $i++) { if ($nb[$i] -ne $b[$i]) { $same = $false; break } }
' {0}' -f $(if ($same) { 'да (0..0x4EAB7 идентичны)' } else { 'НЕТ — различия!' })
'--- хвост (меню) в новом файле:'
$t = [Text.Encoding]::ASCII.GetString($nb[$off..($nb.Length-1)])
' [' + (($t -replace "`n", '\n') -replace "`0", '<NUL>') + ']'
+53
View File
@@ -0,0 +1,53 @@
# Патч Xorboot-конфигов: пункты Ventoy и Kaspersky -> наши переходники.
$ErrorActionPreference = 'Stop'
$out = 'C:\PF\KRD\images\xor'
New-Item -ItemType Directory -Force $out | Out-Null
function Set-Path16([byte[]]$b, [int]$base, [string]$path) {
$slot = 0x130 - 0xBA # размер поля пути в байтах
$bytes = [Text.Encoding]::Unicode.GetBytes($path)
if ($bytes.Length + 2 -gt $slot) { throw "путь слишком длинный: $path ($($bytes.Length+2) > $slot)" }
for ($i = 0; $i -lt $slot; $i++) { $b[$base + 0xBA + $i] = 0 }
[Array]::Copy($bytes, 0, $b, $base + 0xBA, $bytes.Length)
}
$plan = @(
@{ src='F:\efi\Boot\x86.xor'; dst="$out\x86.xor";
ventoyRec=5; ventoyPath='/efi/Paravis/Boot/loaders/xb32/ventoy.efi';
krdRec=6; krdPath='/efi/Paravis/Boot/loaders/xb32/krd.efi' },
@{ src='F:\efi\Boot\x64.xor'; dst="$out\x64.xor";
ventoyRec=3; ventoyPath='/efi/Paravis/Boot/loaders/xb64/ventoy.efi';
krdRec=4; krdPath='/efi/Paravis/Boot/loaders/xb64/krd.efi' }
)
foreach ($p in $plan) {
$b = [IO.File]::ReadAllBytes($p.src)
"--- $($p.src): $($b.Length) байт"
# Ventoy: только путь (тип уже 0 = загрузка файла)
$base = $p.ventoyRec * 0x200
if ($b[$base + 0x80] -ne 0x00) { throw "запись Ventoy #$($p.ventoyRec) не типа 0 (0x$('{0:X2}' -f $b[$base+0x80]))" }
Set-Path16 $b $base $p.ventoyPath
# Kaspersky: тип 0x04 (linux) -> 0x00 (файл), путь -> переходник
$base = $p.krdRec * 0x200
if ($b[$base + 0x80] -ne 0x04) { throw "запись KRD #$($p.krdRec) не типа 4" }
$b[$base + 0x80] = 0x00
Set-Path16 $b $base $p.krdPath
[IO.File]::WriteAllBytes($p.dst, $b)
# контроль
foreach ($r in @($p.ventoyRec, $p.krdRec)) {
$bs = $r * 0x200
$type = $b[$bs + 0x80]
$q = $bs + 0xBA; $chars = @()
while ($q -lt $bs + 0x130) {
$c = [BitConverter]::ToUInt16($b, $q); if ($c -eq 0) { break }
$chars += [char]$c; $q += 2
}
' #{0}: type=0x{1:X2} path={2}' -f $r, $type, (-join $chars)
}
}
'--- файлы:'
Get-ChildItem $out -File | Select-Object Name,Length | Format-Table -AutoSize
+17
View File
@@ -0,0 +1,17 @@
# Поиск имён шрифтов в PSD (UTF-16 LE/BE и ASCII), только внутри C:\PF\PSD
$files = @('C:\PF\PSD\main\main.psd','C:\PF\PSD\UEFI\x64\main\main.psd','C:\PF\PSD\UEFI\x86\main\main.psd')
$names = 'Inter','Segoe','Roboto','PT Sans','Open Sans','Arial','Montserrat','Gilroy','Gotham','Proxima','Futura','Helvetica','SF Pro','Tahoma','Verdana','Noto Sans','Source Sans','Ubuntu','Lato','Manrope','Golos','GolosText','IBM Plex','Rubik','Exo','Museo','Circe','Geometria','PT Root','Suisse','Graphik','TT Norms','Gilroy'
foreach ($f in $files) {
"=== $f"
$b = [IO.File]::ReadAllBytes($f)
$uLE = [Text.Encoding]::Unicode.GetString($b)
$uBE = [Text.Encoding]::BigEndianUnicode.GetString($b)
$asc = [Text.Encoding]::ASCII.GetString($b)
foreach ($n in $names) {
$c = @()
if ($asc.Contains($n)) { $c += 'ascii' }
if ($uLE.Contains($n)) { $c += 'utf16le' }
if ($uBE.Contains($n)) { $c += 'utf16be' }
if ($c.Count) { " {0}: {1}" -f $n, ($c -join ', ') }
}
}
+41
View File
@@ -0,0 +1,41 @@
# Восстановление x86.xor: оригинал (KRD 18) + рабочая правка Ventoy.
$ErrorActionPreference = 'Stop'
$bak = 'C:\PF\flash-backup-2026-10-30-2\01-PARAVIS-F\efi\Boot\x86.xor'
$dst = 'F:\efi\Paravis\Boot\loaders\xb32' # не используется, просто место
$cur = 'F:\efi\Boot\x86.xor'
$keep = 'C:\PF\Ventoy\backup\x86.xor.editor-ventoy.bin'
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена' }
# сохранить текущий (после редактора) на всякий случай
Copy-Item $cur $keep -Force
$b = [IO.File]::ReadAllBytes($bak)
$rec = 5 * 0x200 # запись Ventoy
$path = '/EFI/BOOT/grubia32.efi'
$bytes = [Text.Encoding]::Unicode.GetBytes($path)
$slot = 0x130 - 0xBA
if ($bytes.Length + 2 -gt $slot) { throw 'путь не влезает' }
for ($i = 0; $i -lt $slot; $i++) { $b[$rec + 0xBA + $i] = 0 }
[Array]::Copy($bytes, 0, $b, $rec + 0xBA, $bytes.Length)
[IO.File]::WriteAllBytes($cur, $b)
# контроль
$nb = [IO.File]::ReadAllBytes($cur)
"--- записан: {0:N0} байт" -f $nb.Length
$u = [Text.Encoding]::Unicode.GetString($nb)
'--- пути (UTF-16):'
$i = 0
while ($i -lt $u.Length - 2) {
$c = [int]$u[$i]
if ($c -ge 32 -and $c -lt 127) {
$j = $i
while ($j -lt $u.Length -and [int]$u[$j] -ge 32 -and [int]$u[$j] -lt 127) { $j++ }
if ($j - $i -ge 5) { ' 0x{0:X4}: {1}' -f ($i*2), $u.Substring($i, $j-$i) }
$i = $j
} else { $i++ }
}
'--- cmdline/initrd (ASCII):'
$s = [Text.Encoding]::ASCII.GetString($nb)
([regex]::Matches($s,'[\x20-\x7E]{12,}') | ForEach-Object { $_.Value }) | Select-Object -First 5 | ForEach-Object { ' ' + $_ }
+25
View File
@@ -0,0 +1,25 @@
import numpy as np
from PIL import Image
ref = Image.open(r'C:\PF\flash-logo-block-dark.png').convert('RGB')
out = Image.open(r'C:\PF\flash-logo-block-dark-4x.png').convert('RGB')
ref_g = np.asarray(ref.convert('L')) > 60
small = out.resize(ref.size, Image.BOX)
out_g = np.asarray(small.convert('L')) > 100
lost = ref_g & ~out_g # ink in original that disappeared
extra = out_g & ~ref_g # ink that appeared where the original had none
vis = np.zeros(ref_g.shape + (3,), dtype=np.uint8)
vis[ref_g] = (90, 90, 90) # kept/still ink -> grey
vis[extra] = (0, 255, 60) # new ink -> green
vis[lost] = (255, 40, 40) # lost ink -> red
img = Image.fromarray(vis)
img.save(r'C:\PF\tools\diff_full.png')
img.resize((1600, round(ref.size[1] * 1600 / ref.size[0])), Image.LANCZOS).save(r'C:\PF\tools\diff_small.png')
# text zoom, 2x for inspection
img.crop((80, 120, 700, 310)).resize((1240, 380), Image.NEAREST).save(r'C:\PF\tools\diff_text.png')
img.crop((0, 60, 200, 340)).resize((400, 560), Image.NEAREST).save(r'C:\PF\tools\diff_cap.png')
print('lost px', int(lost.sum()), 'extra px', int(extra.sum()), 'ink', int(ref_g.sum()))
+298
View File
@@ -0,0 +1,298 @@
"""Vector rebuild + high quality upscale for a flat two-colour logo.
Steps
1. binarise (the source is 1-bit: #000000 / #6F849C, no anti-aliasing)
2. optional morphological closing limited to a region (fills hairline cracks)
3. trace boundaries, simplify with Douglas-Peucker at a tight tolerance
4. round the residual pixel staircases: vertices with a small turn angle get a
tiny quadratic-Bezier fillet, real corners (>= corner_deg) stay razor sharp
5. render with supersampled anti-aliasing at the requested scale
Usage:
python vector_up2.py in.png out.png [--scale 4] [--eps 0.6] [--round 1.6]
[--corner-deg 55] [--close R:x0,y0,x1,y1] [--svg out.svg]
"""
from __future__ import annotations
import math
import sys
import cv2
import numpy as np
from PIL import Image, ImageDraw
Image.MAX_IMAGE_PIXELS = None
BG = (0, 0, 0)
def binarise(img: Image.Image, thresh: int = 60) -> np.ndarray:
return (np.asarray(img.convert("L")) > thresh).astype(np.uint8)
def close_region(mask: np.ndarray, radius: int, box: tuple[int, int, int, int]) -> np.ndarray:
x0, y0, x1, y1 = box
x0, y0 = max(0, x0), max(0, y0)
x1, y1 = min(mask.shape[1], x1), min(mask.shape[0], y1)
sub = mask[y0:y1, x0:x1]
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
out = mask.copy()
out[y0:y1, x0:x1] = cv2.morphologyEx(sub, cv2.MORPH_CLOSE, k)
return out
def smooth_dense(pts: np.ndarray, window: int) -> np.ndarray:
"""Circular moving average over a dense (per-pixel) closed contour."""
if window < 3 or len(pts) < window * 3:
return pts
n = len(pts)
pad = window // 2
ext = np.concatenate([pts[-pad:], pts, pts[:pad]], axis=0)
ker = np.ones(window, dtype=np.float64) / window
x = np.convolve(ext[:, 0], ker, mode="valid")
y = np.convolve(ext[:, 1], ker, mode="valid")
return np.stack([x, y], axis=1)[:n]
def trace(mask: np.ndarray, eps: float, smooth: int = 0,
zone: tuple | None = None,
alt: tuple | None = None) -> tuple[list[np.ndarray], list[int]]:
"""Trace + simplify.
`zone` = (x0, y0, x1, y1) and `alt` = (eps, smooth) let contours inside that
box use different simplification settings (fine detail zone).
"""
contours, _ = cv2.findContours(mask * 255, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
polys: list[np.ndarray] = []
for cnt in contours:
if len(cnt) < 3:
continue
this_eps, this_smooth = eps, smooth
if zone is not None and alt is not None:
x, y, w, h = cv2.boundingRect(cnt)
if x >= zone[0] and y >= zone[1] and x + w <= zone[2] and y + h <= zone[3]:
this_eps, this_smooth = alt
dense = cnt.reshape(-1, 2).astype(np.float64)
if this_smooth >= 3:
dense = smooth_dense(dense, this_smooth)
approx = cv2.approxPolyDP(dense.reshape(-1, 1, 2).astype(np.float32), this_eps, True)
approx = approx.reshape(-1, 2).astype(np.float64)
else:
approx = cv2.approxPolyDP(cnt, this_eps, True).reshape(-1, 2).astype(np.float64)
if len(approx) < 3:
approx = dense
if len(approx) < 3:
continue
if abs(shoelace(approx)) < 3.0:
continue
polys.append(approx)
depths = [0] * len(polys)
for i, p in enumerate(polys):
pt = (float(p[0][0]), float(p[0][1]))
depths[i] = sum(
1
for j, q in enumerate(polys)
if j != i and cv2.pointPolygonTest(q.astype(np.int32), pt, False) > 0
)
order = sorted(range(len(polys)), key=lambda k: depths[k])
return [polys[k] for k in order], [depths[k] for k in order]
def shoelace(p: np.ndarray) -> float:
x, y = p[:, 0], p[:, 1]
return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))
def round_corners(poly: np.ndarray, radius: float, corner_deg: float, steps: int = 4) -> list[tuple[float, float]]:
"""Fillet shallow vertices, keep sharp corners untouched."""
n = len(poly)
cos_limit = math.cos(math.radians(corner_deg))
out: list[tuple[float, float]] = []
for i in range(n):
prev, cur, nxt = poly[i - 1], poly[i], poly[(i + 1) % n]
v1 = cur - prev
v2 = nxt - cur
l1 = float(np.hypot(*v1))
l2 = float(np.hypot(*v2))
if l1 < 1e-9 or l2 < 1e-9:
out.append((float(cur[0]), float(cur[1])))
continue
u1 = v1 / l1
u2 = v2 / l2
cos_turn = float(np.dot(u1, u2))
# cos ~1 -> straight ahead, cos ~-1 -> full reversal, 0 -> 90 deg
if cos_turn < cos_limit: # sharp corner: keep it
out.append((float(cur[0]), float(cur[1])))
continue
t = min(radius, 0.45 * l1, 0.45 * l2, 0.5 * l2 if l1 > 0 else radius)
if t < 0.15:
out.append((float(cur[0]), float(cur[1])))
continue
p1 = cur - u1 * t
p2 = cur + u2 * t
for s in range(steps + 1):
w = s / steps
a = (1 - w) ** 2
b = 2 * (1 - w) * w
c = w * w
out.append((float(a * p1[0] + b * cur[0] + c * p2[0]),
float(a * p1[1] + b * cur[1] + c * p2[1])))
return out
def offset_polygon(poly: np.ndarray, d: float) -> np.ndarray:
"""Miter-offset a closed polygon by d pixels along its outward normal."""
p = np.asarray(poly, dtype=np.float64)
n = len(p)
if n < 3 or d == 0:
return p
s = shoelace(p)
nxt = np.roll(p, -1, axis=0)
prv = np.roll(p, 1, axis=0)
e1 = p - prv # incoming edge
e2 = nxt - p # outgoing edge
l1 = np.hypot(e1[:, 0], e1[:, 1])
l2 = np.hypot(e2[:, 0], e2[:, 1])
l1[l1 == 0] = 1
l2[l2 == 0] = 1
e1 /= l1[:, None]
e2 /= l2[:, None]
if s > 0: # y-down: clockwise on screen -> outward is (dy, -dx)
n1 = np.stack([e1[:, 1], -e1[:, 0]], axis=1)
n2 = np.stack([e2[:, 1], -e2[:, 0]], axis=1)
else:
n1 = np.stack([-e1[:, 1], e1[:, 0]], axis=1)
n2 = np.stack([-e2[:, 1], e2[:, 0]], axis=1)
dot = np.clip((n1 * n2).sum(axis=1), -0.999, 0.999)
miter = (n1 + n2) / (1 + dot)[:, None]
length = np.hypot(miter[:, 0], miter[:, 1])
limit = 3.0
scale = np.where(length > limit, limit / np.maximum(length, 1e-9), 1.0)
return p + miter * (d * scale)[:, None]
def iou(alpha_small: Image.Image, ref: np.ndarray, thresh: int = 128) -> float:
a = np.asarray(alpha_small) > thresh
b = ref.astype(bool)
union = (a | b).sum()
return float((a & b).sum() / union) if union else 0.0
def render(polys, depths, size, scale: float, supersample: int) -> Image.Image:
W, H = int(round(size[0] * scale)), int(round(size[1] * scale))
f = supersample
mask = Image.new("L", (W * f, H * f), 0)
draw = ImageDraw.Draw(mask)
for poly, depth in zip(polys, depths):
pts = [(x * scale * f, y * scale * f) for x, y in poly]
if len(pts) >= 3:
draw.polygon(pts, fill=0 if depth % 2 else 255)
if f > 1:
mask = mask.reduce(f) if f in (2, 4, 8) else mask.resize((W, H), Image.BOX)
return mask
def to_rgb(alpha: Image.Image, ink: tuple[int, int, int]) -> Image.Image:
a = np.asarray(alpha, dtype=np.float32)[..., None] / 255.0
arr = np.empty(a.shape[:2] + (3,), dtype=np.uint8)
for c in range(3):
arr[..., c] = np.clip(a[..., 0] * ink[c] + (1 - a[..., 0]) * BG[c], 0, 255).astype(np.uint8)
return Image.fromarray(arr, "RGB")
def write_svg(path, polys, size, color):
parts = []
for poly in polys:
pts = " L ".join(f"{x:.2f} {y:.2f}" for x, y in poly)
parts.append(f"M {pts} Z")
svg = (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {size[0]} {size[1]}" '
f'width="{size[0]}" height="{size[1]}">\n'
f'<rect width="{size[0]}" height="{size[1]}" fill="#000"/>\n'
f'<path fill="{color}" fill-rule="evenodd" d="{" ".join(parts)}"/>\n</svg>\n'
)
with open(path, "w", encoding="utf-8") as fh:
fh.write(svg)
def main(argv: list[str]) -> int:
a = list(argv)
scale, eps, rnd, corner_deg, ss, close, svg_path, smooth = 4.0, 0.6, 1.6, 55.0, 2, None, None, 0
offset = 0.5
def take(flag, cast=float):
nonlocal a
i = a.index(flag)
val = cast(a[i + 1])
del a[i:i + 2]
return val
if "--scale" in a: scale = take("--scale")
if "--eps" in a: eps = take("--eps")
if "--round" in a: rnd = take("--round")
if "--smooth" in a: smooth = take("--smooth", int)
if "--offset" in a: offset = take("--offset")
if "--corner-deg" in a: corner_deg = take("--corner-deg")
if "--supersample" in a: ss = take("--supersample", int)
if "--svg" in a: svg_path = a[a.index("--svg") + 1]; del a[a.index("--svg"):a.index("--svg") + 2]
if "--close" in a:
raw = a[a.index("--close") + 1]
del a[a.index("--close"):a.index("--close") + 2]
r, box = raw.split(":")
close = (int(r), tuple(int(v) for v in box.split(",")))
zone, alt = None, None
if "--zone" in a:
raw = a[a.index("--zone") + 1]
del a[a.index("--zone"):a.index("--zone") + 2]
zone = tuple(int(v) for v in raw.split(","))
alt = (1.0, 0) # replaced below if given
if "--zone-eps" in a:
alt = (take("--zone-eps"), alt[1] if alt else 0)
if "--zone-smooth" in a:
alt = (alt[0] if alt else 1.0, take("--zone-smooth", int))
if len(a) != 3:
print(__doc__)
return 2
src_path, dst_path = a[1], a[2]
src = Image.open(src_path).convert("RGB")
mask = binarise(src)
if close is not None:
mask = close_region(mask, close[0], close[1])
print("closing applied:", close)
ink = (111, 132, 156)
polys, depths = trace(mask, eps, smooth, zone, alt)
if rnd > 0:
polys = [round_corners(p, rnd, corner_deg) for p in polys]
if offset != 0.0:
base_alpha = render(polys, depths, src.size, 1.0, 2).resize(src.size, Image.BOX)
base_iou = iou(base_alpha, mask)
best = (base_iou, 0.0, polys)
for sign in (1.0, -1.0):
cand = [offset_polygon(p, sign * offset) for p in polys]
a1 = render(cand, depths, src.size, 1.0, 2).resize(src.size, Image.BOX)
score = iou(a1, mask)
if score > best[0]:
best = (score, sign * offset, cand)
print(f"offset chosen: {best[1]:+.2f}px IoU {base_iou:.4f} -> {best[0]:.4f}")
polys = best[2]
print(f"contours: {len(polys)} eps={eps} round={rnd}")
alpha = render(polys, depths, src.size, scale, ss)
out = to_rgb(alpha, ink)
out.save(dst_path, "PNG", optimize=True)
print(f"written: {dst_path} {out.size[0]}x{out.size[1]}")
if svg_path:
write_svg(svg_path, polys, src.size, "#%02x%02x%02x" % ink)
print(f"written: {svg_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+8
View File
@@ -0,0 +1,8 @@
@echo off
net session >nul 2>&1
if not "%errorlevel%"=="0" (
powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
powershell -NoProfile -ExecutionPolicy Bypass -File "C:\PF\vm-start.ps1"
if errorlevel 1 pause
+126
View File
@@ -0,0 +1,126 @@
param(
[switch]$Uefi
)
$ErrorActionPreference = 'Stop'
$vmrun = 'C:\Program Files\VMware\VMware Workstation\vmrun.exe'
$vmx = if ($Uefi) {
'D:\Paravis\Documents\Virtual Machines\Windows 10 x64\Windows 10 x64.vmx'
} else {
'D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx'
}
$hGuid = '\\?\Volume{ef6d2f86-0000-0000-0000-100204000000}\'
$fGuid = '\\?\Volume{ef6d2f86-0000-0000-0000-100000000000}\'
function Get-RunningVms {
try { return ((& $vmrun -T ws list 2>$null) -join "`n") } catch { return '' }
}
function Test-VmRunning {
return ((Get-RunningVms) -match [regex]::Escape($vmx))
}
function Test-Drive([string]$letter) {
try { return (Test-Path ($letter + ':\')) } catch { return $false }
}
function Restore-Drive([string]$letter, [string]$guid) {
if (Test-Drive $letter) { return $true }
for ($i = 1; $i -le 10; $i++) {
try { & mountvol ($letter + ':') $guid 2>$null | Out-Null } catch { }
if (Test-Drive $letter) { return $true }
Start-Sleep -Seconds 1
}
return $false
}
function Restore-Volumes {
# H: возвращаем сразу; F: после работы VMware часто требует rescan
$okH = Restore-Drive 'H' $hGuid
if (-not (Test-Drive 'F')) {
try {
$dp = "rescan`r`nexit`r`n"
$dp | Out-File "$env:TEMP\vm-rescan.txt" -Encoding ASCII
& diskpart /s "$env:TEMP\vm-rescan.txt" 2>$null | Out-Null
} catch { }
Start-Sleep -Seconds 3
Restore-Drive 'F' $fGuid | Out-Null
}
if (-not (Test-Drive 'H')) { Restore-Drive 'H' $hGuid | Out-Null }
$okF = Test-Drive 'F'
if ($okF) { Write-Host 'F: восстановлен.' -ForegroundColor Green }
else {
Write-Host 'ВНИМАНИЕ: не удалось вернуть F:. Верните вручную:' -ForegroundColor Yellow
Write-Host (' mountvol F: ' + $fGuid)
}
if ($okH) { Write-Host 'H: восстановлен.' -ForegroundColor Green }
else {
Write-Host 'ВНИМАНИЕ: не удалось вернуть H:. Верните вручную:' -ForegroundColor Yellow
Write-Host (' mountvol H: ' + $hGuid)
}
}
$title = if ($Uefi) { 'VM UEFI (Paravis)' } else { 'VM BIOS (Paravis)' }
$Host.UI.RawUI.WindowTitle = $title
Write-Host ('=== ' + $title + ' ===') -ForegroundColor Cyan
Write-Host ('ВМ: ' + $vmx)
# Уже запущена другая ВМ — не трогаем H:
if (Test-VmRunning) {
Write-Host 'Эта ВМ уже запущена. Ничего не меняю.' -ForegroundColor Yellow
Start-Sleep -Seconds 3
exit 0
}
$other = Get-RunningVms
if ($other -match '\.vmx') {
Write-Host 'Уже запущена другая ВМ. Закройте её и запустите снова.' -ForegroundColor Yellow
Start-Sleep -Seconds 5
exit 1
}
$removed = $false
try {
if (Test-Drive 'H') {
Write-Host 'Снимаю букву H: (том DATA)...'
& mountvol H: /p 2>$null | Out-Null
Start-Sleep -Milliseconds 800
if (Test-Drive 'H') { throw 'Не удалось снять H:. Возможно, том занят.' }
$removed = $true
Write-Host 'H: снят.' -ForegroundColor Green
} else {
Write-Host 'H: уже снят.'
}
Write-Host 'Запускаю ВМ...'
& $vmrun -T ws start $vmx | Out-Null
if ($LASTEXITCODE -ne 0) { throw ('vmrun start вернул код ' + $LASTEXITCODE) }
# vmrun list может отставать; ориентируемся на процесс vmware-vmx
$started = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
if (Get-Process vmware-vmx -ErrorAction SilentlyContinue) { $started = $true; break }
}
if (-not $started) { throw 'ВМ не запустилась. Смотрите vmware.log.' }
Write-Host 'ВМ запущена. Жду выключения...' -ForegroundColor Green
Write-Host '(это окно можно свернуть; F: и H: вернутся автоматически)'
while ($true) {
Start-Sleep -Seconds 5
$proc = Get-Process vmware-vmx -ErrorAction SilentlyContinue
$listed = Test-VmRunning
if (-not $proc -and -not $listed) { break }
}
Write-Host 'ВМ выключена.'
}
catch {
Write-Host ('ОШИБКА: ' + $_.Exception.Message) -ForegroundColor Red
}
finally {
Write-Host 'Возвращаю тома...'
Restore-Volumes
}
Start-Sleep -Seconds 3
+8
View File
@@ -0,0 +1,8 @@
@echo off
net session >nul 2>&1
if not "%errorlevel%"=="0" (
powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
powershell -NoProfile -ExecutionPolicy Bypass -File "C:\PF\vm-start.ps1" -Uefi
if errorlevel 1 pause
+38
View File
@@ -0,0 +1,38 @@
# Заливка ia32: конфиг без KRD + картинки без строки Kaspersky.
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена' }
# 1) конфиг
Copy-Item 'C:\PF\KRD\images\xor\x86.xor' 'F:\efi\Boot\x86.xor' -Force
' x86.xor: {0:N0} байт' -f (Get-Item 'F:\efi\Boot\x86.xor').Length
# 2) картинки (PNG -> BMP с исходным заголовком)
$map = @(
@{ png='C:\PF\KRD\images\x86-1-nokrd.png'; src='C:\PF\PSD\UEFI\x86\main\main1.bmp'; dst='F:\efi\Boot\1x86.bmp' },
@{ png='C:\PF\KRD\images\x86-2-nokrd.png'; src='C:\PF\PSD\UEFI\x86\main\main2.bmp'; dst='F:\efi\Boot\2x86.bmp' }
)
foreach ($m in $map) {
$srcBytes = [IO.File]::ReadAllBytes($m.src)
$off = [BitConverter]::ToUInt32($srcBytes, 10)
$w = [BitConverter]::ToInt32($srcBytes, 18); $h = [BitConverter]::ToInt32($srcBytes, 22)
$img = [System.Drawing.Image]::FromFile($m.png)
$bmp = New-Object System.Drawing.Bitmap $img; $img.Dispose()
$rowBytes = $w * 3
$pix = New-Object byte[] ($rowBytes * $h)
for ($y = 0; $y -lt $h; $y++) {
$srcY = $h - 1 - $y
for ($x = 0; $x -lt $w; $x++) {
$c = $bmp.GetPixel($x, $srcY)
$o = $y * $rowBytes + $x * 3
$pix[$o] = $c.B; $pix[$o+1] = $c.G; $pix[$o+2] = $c.R
}
}
$bmp.Dispose()
$outBytes = New-Object byte[] $srcBytes.Length
[Array]::Copy($srcBytes, $outBytes, $srcBytes.Length)
[Array]::Copy($pix, 0, $outBytes, [int]$off, $pix.Length)
[IO.File]::WriteAllBytes($m.dst, $outBytes)
' {0}: {1:N0} байт' -f $m.dst, (Get-Item $m.dst).Length
}
'--- свободно: {0:N0} МБ' -f ((Get-Volume -DriveLetter F).SizeRemaining/1MB)
+40
View File
@@ -0,0 +1,40 @@
# Удаление пункта KRD (запись #6) из x86.xor + сборка тестового образа.
$ErrorActionPreference = 'Stop'
$src = 'F:\efi\Boot\x86.xor'
$bak = 'C:\PF\Ventoy\backup\x86.xor.before-remove-krd.bin'
$out = 'C:\PF\KRD\images\xor\x86.xor'
New-Item -ItemType Directory -Force (Split-Path $out) | Out-Null
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена' }
Copy-Item $src $bak -Force
$b = [IO.File]::ReadAllBytes($src)
$rec = 0x200
$idx = 6
# проверим, что это действительно KRD
$p = $idx*$rec + 0xBA; $ch = @()
while ($p -lt $idx*$rec + 0x130) { $c=[BitConverter]::ToUInt16($b,$p); if($c -eq 0){break}; $ch+=[char]$c; $p+=2 }
if ((-join $ch) -notlike '*KRD*') { throw "запись #6 не KRD: " + (-join $ch) }
"--- удаляю запись #6 ($(-join $ch))"
# сдвигаем записи 7..10 на место 6..9
for ($r = $idx; $r -lt 10; $r++) {
[Array]::Copy($b, ($r+1)*$rec, $b, $r*$rec, $rec)
}
# последнюю запись (бывшая #10) обнуляем
for ($i = 0; $i -lt $rec; $i++) { $b[10*$rec + $i] = 0 }
# счётчик (0x10) уменьшаем на 1
"--- счётчик до: 0x{0:X2}" -f $b[0x10]
$b[0x10] = $b[0x10] - 1
"--- счётчик после: 0x{0:X2}" -f $b[0x10]
[IO.File]::WriteAllBytes($out, $b)
"--- записан: $out"
# контроль списка
for ($r = 0; $r -lt 11; $r++) {
$base = $r*$rec
$p = $base + 0xBA; $ch = @()
while ($p -lt $base + 0x130) { $c=[BitConverter]::ToUInt16($b,$p); if($c -eq 0){break}; $ch+=[char]$c; $p+=2 }
' #{0} type=0x{1:X2} path={2}' -f $r, $b[$base+0x80], (-join $ch)
}
+66
View File
@@ -0,0 +1,66 @@
# Сборка BMP из PNG с сохранением оригинального заголовка + заливка на флешку.
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
$work = 'C:\PF\KRD\images'
$bak = 'C:\PF\Ventoy\backup\xor-images'
New-Item -ItemType Directory -Force $bak | Out-Null
$map = @(
@{ png = 'legacy-1'; src = 'C:\PF\PSD\main\main1.bmp'; dst = 'F:\efi\Paravis\Boot\xor\Main1.bmp' },
@{ png = 'legacy-2'; src = 'C:\PF\PSD\main\main2.bmp'; dst = 'F:\efi\Paravis\Boot\xor\Main2.bmp' },
@{ png = 'x64-1'; src = 'C:\PF\PSD\UEFI\x64\main\main1.bmp'; dst = 'F:\efi\Boot\1x64.bmp' },
@{ png = 'x64-2'; src = 'C:\PF\PSD\UEFI\x64\main\main2.bmp'; dst = 'F:\efi\Boot\2x64.bmp' },
@{ png = 'x86-1'; src = 'C:\PF\PSD\UEFI\x86\main\main1.bmp'; dst = 'F:\efi\Boot\1x86.bmp' },
@{ png = 'x86-2'; src = 'C:\PF\PSD\UEFI\x86\main\main2.bmp'; dst = 'F:\efi\Boot\2x86.bmp' }
)
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена — сначала выключите' }
foreach ($m in $map) {
$pngPath = Join-Path $work ($m.png + '.png')
$srcBytes = [IO.File]::ReadAllBytes($m.src)
$off = [BitConverter]::ToUInt32($srcBytes, 10)
$w = [BitConverter]::ToInt32($srcBytes, 18)
$h = [BitConverter]::ToInt32($srcBytes, 22)
$img = [System.Drawing.Image]::FromFile($pngPath)
if ($img.Width -ne $w -or $img.Height -ne $h) { throw "$($m.png): размер $($img.Width)x$($img.Height) != ${w}x${h}" }
$bmp = New-Object System.Drawing.Bitmap $img
$img.Dispose()
$rowBytes = $w * 3
$pix = New-Object byte[] ($rowBytes * $h)
for ($y = 0; $y -lt $h; $y++) {
$srcY = $h - 1 - $y # BMP хранится снизу вверх
for ($x = 0; $x -lt $w; $x++) {
$c = $bmp.GetPixel($x, $srcY)
$o = $y * $rowBytes + $x * 3
$pix[$o] = $c.B
$pix[$o + 1] = $c.G
$pix[$o + 2] = $c.R
}
}
$bmp.Dispose()
$outBytes = New-Object byte[] $srcBytes.Length
[Array]::Copy($srcBytes, $outBytes, $srcBytes.Length)
[Array]::Copy($pix, 0, $outBytes, [int]$off, $pix.Length)
$outPath = Join-Path $work ($m.png + '.bmp')
[IO.File]::WriteAllBytes($outPath, $outBytes)
"--- {0}: {1:N0} байт (эталон {2:N0})" -f $m.png, $outBytes.Length, $srcBytes.Length
}
'--- заливка на флешку (с бэкапом):'
foreach ($m in $map) {
$b = Split-Path $m.dst -Leaf
if (Test-Path $m.dst) {
Copy-Item $m.dst (Join-Path $bak $b) -Force
}
Copy-Item (Join-Path $work ($m.png + '.bmp')) $m.dst -Force
$i = Get-Item $m.dst
" {0,-24} {1:N0} байт sha256={2}" -f $m.dst, $i.Length, (Get-FileHash $m.dst -Algorithm SHA256).Hash.Substring(0,12)
}
'--- бэкапы:'
Get-ChildItem $bak -File | Select-Object Name,Length | Format-Table -AutoSize
+15
View File
@@ -0,0 +1,15 @@
# Сверка картинок на флешке с исходниками PSD и сбор параметров (цвета, области текста).
$pairs = @(
@('legacy-normal', 'F:\efi\Paravis\Boot\xor\Main1.bmp', 'C:\PF\PSD\main\main1.bmp'),
@('legacy-high', 'F:\efi\Paravis\Boot\xor\Main2.bmp', 'C:\PF\PSD\main\main2.bmp'),
@('x64-normal', 'F:\efi\Boot\1x64.bmp', 'C:\PF\PSD\UEFI\x64\main\main1.bmp'),
@('x64-high', 'F:\efi\Boot\2x64.bmp', 'C:\PF\PSD\UEFI\x64\main\main2.bmp'),
@('x86-normal', 'F:\efi\Boot\1x86.bmp', 'C:\PF\PSD\UEFI\x86\main\main1.bmp'),
@('x86-high', 'F:\efi\Boot\2x86.bmp', 'C:\PF\PSD\UEFI\x86\main\main2.bmp')
)
foreach ($p in $pairs) {
$n = $p[0]; $flash = $p[1]; $psd = $p[2]
$h1 = if (Test-Path $flash) { (Get-FileHash $flash -Algorithm SHA256).Hash.Substring(0,16) } else { 'нет файла' }
$h2 = if (Test-Path $psd) { (Get-FileHash $psd -Algorithm SHA256).Hash.Substring(0,16) } else { 'нет файла' }
' {0,-14} flash={1} psd={2} {3}' -f $n, $h1, $h2, $(if ($h1 -eq $h2) { 'ИДЕНТИЧНЫ' } else { 'различаются' })
}
+35
View File
@@ -0,0 +1,35 @@
# Заливка ia32-картинок (KRD 18) на флешку.
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
$work = 'C:\PF\KRD\images'
$map = @(
@{ png='x86-1'; src='C:\PF\PSD\UEFI\x86\main\main1.bmp'; dst='F:\efi\Boot\1x86.bmp' },
@{ png='x86-2'; src='C:\PF\PSD\UEFI\x86\main\main2.bmp'; dst='F:\efi\Boot\2x86.bmp' }
)
if (Get-Process -Name vmware-vmx -ErrorAction SilentlyContinue) { throw 'VM запущена' }
foreach ($m in $map) {
$srcBytes = [IO.File]::ReadAllBytes($m.src)
$off = [BitConverter]::ToUInt32($srcBytes, 10)
$w = [BitConverter]::ToInt32($srcBytes, 18); $h = [BitConverter]::ToInt32($srcBytes, 22)
$img = [System.Drawing.Image]::FromFile((Join-Path $work ($m.png + '.png')))
$bmp = New-Object System.Drawing.Bitmap $img; $img.Dispose()
$rowBytes = $w * 3
$pix = New-Object byte[] ($rowBytes * $h)
for ($y = 0; $y -lt $h; $y++) {
$srcY = $h - 1 - $y
for ($x = 0; $x -lt $w; $x++) {
$c = $bmp.GetPixel($x, $srcY)
$o = $y * $rowBytes + $x * 3
$pix[$o] = $c.B; $pix[$o+1] = $c.G; $pix[$o+2] = $c.R
}
}
$bmp.Dispose()
$outBytes = New-Object byte[] $srcBytes.Length
[Array]::Copy($srcBytes, $outBytes, $srcBytes.Length)
[Array]::Copy($pix, 0, $outBytes, [int]$off, $pix.Length)
$outPath = Join-Path $work ($m.png + '.bmp')
[IO.File]::WriteAllBytes($outPath, $outBytes)
Copy-Item $outPath $m.dst -Force
' {0} -> {1} {2:N0} байт' -f $m.png, $m.dst, (Get-Item $m.dst).Length
}
'--- свободно: {0:N0} МБ' -f ((Get-Volume -DriveLetter F).SizeRemaining/1MB)