Set UTF-8 encoding [Console]::OutputEncoding = [System.Text.Encoding]::UTF8…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::InputEncoding = [System.Text.Encoding]::UTF8
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process powershell.exe "-ExecutionPolicy Bypass -File "$PSCommandPath"" -Verb RunAs
exit
}
Add-Type @" using System; using System.Runtime.InteropServices; public class Win32 { [DllImport("user32.dll")] public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] public static extern bool DeleteMenu(IntPtr hMenu, int uPosition, int uFlags); } "@
pid).MainWindowHandle hwnd, menu, 0xF060, 0x00000000) | Out-Null # SC_CLOSE
Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class ConsoleHandler { public delegate bool HandlerRoutine(int CtrlType); [DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); } "@
handler = [ConsoleHandler+HandlerRoutine]{ param([int]ctrlType) switch (ctrlType) { 0 { Write-Host "`nНет."; return true } 1 { Write-Host "`nНет."; return true } default { return false } } }
[ConsoleHandler]::SetConsoleCtrlHandler(true) | Out-Null
function Show-Progress { param(target) try { source -Force file.Length $bufferSize = 1MB
attrib -H -S -R "`"$source`"" | Out-Null
if (Test-Path $target) {
attrib -H -S -R "`"$target`"" | Out-Null
Remove-Item $target -Force
Start-Sleep -Milliseconds 500
}
$inputStream = [System.IO.File]::OpenRead($source)
$outputStream = [System.IO.File]::OpenWrite($target)
$buffer = New-Object byte[] $bufferSize
$totalRead = 0
while ($totalRead -lt $fileSize) {
$bytesRead = $inputStream.Read($buffer, 0, $bufferSize)
$outputStream.Write($buffer, 0, $bytesRead)
$totalRead += $bytesRead
$percent = ($totalRead / $fileSize) * 100
Write-Progress -Activity "Копирование прошивки" -Status "$([Math]::Round($percent,1))% завершено" -PercentComplete $percent
}
$outputStream.Close()
$inputStream.Close()
attrib +H +S +R "`"$source`"" | Out-Null
attrib +H +S +R "`"$target`"" | Out-Null
Write-Progress -Activity "Копирование прошивки" -Completed
return $true
}
catch {
Write-Host "Ошибка копирования: $_" -ForegroundColor Red
return $false
}
}
function Get-Checksum { param(path) try { originalAttributes = (Get-Item path -Force).Attributes = path -Algorithm SHA256 -ErrorAction Stop).Hash } finally { (Get-Item originalAttributes attrib +H +S +R """ | Out-Null } }
function Wait-ForUSB { param(spinner = @('|', '/', '-', '') $spinnerIndex = 0
while ($true) {
if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
if ($key.Character -eq '-') {
Write-Host "`nПерезапуск скрипта..."
Start-Sleep -Seconds 1
exit 100
}
}
$drive = Get-WmiObject Win32_LogicalDisk |
Where-Object {
$_.DriveType -eq 2 -and
($_.DeviceID.ToUpper() -ne 'Z:') -and
(Test-Path "$($_.DeviceID)\")
} |
Select-Object -First 1
if ($drive) { return $drive }
Write-Host "`r[$($spinner[$spinnerIndex])] Ожидание подключения VTX (прошивка $firmware)... Нажмите '-' для перезапуска" -NoNewline
$spinnerIndex = ($spinnerIndex + 1) % 4
Start-Sleep -Milliseconds 150
}
}
function Safe-Eject { param($driveLetter) try { Start-Sleep -Seconds 2 [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers()
$shell = New-Object -ComObject Shell.Application
$drive = $shell.Namespace(17).ParseName($driveLetter)
if ($drive) {
$drive.InvokeVerb("Eject")
} else {
throw "Не удалось найти $driveLetter для извлечения"
}
$maxRetries = 30
$retryCount = 0
while ((Test-Path $driveLetter) -and ($retryCount -lt $maxRetries)) {
Start-Sleep -Milliseconds 500
$retryCount++
}
if (Test-Path $driveLetter) {
Write-Host "Устройство не извлечено автоматически. Извлеките вручную." -ForegroundColor Yellow
return $false
}
return $true
}
catch {
Write-Host "Ошибка при извлечении: $_" -ForegroundColor Red
return $false
}
}
while (true) { cmd /c cls Write-Host "================= Выбор прошивки =================" -ForegroundColor Cyan firmware = Read-Host "`nВыбери версию прошивки? (12 или 13)" while (firmware -notin '12', '13') { firmware = Read-Host "Некорректный ввод. Введите 12 или 13" }
$sourceFile = Join-Path $PSScriptRoot "Firmware\Avatar_Sky_38.43.$firmware.img"
if (-not (Test-Path $sourceFile)) {
Write-Host "Файл прошивки не найден: $sourceFile" -ForegroundColor Red
Start-Sleep -Seconds 2
continue
}
while ($true) {
cmd /c cls
Write-Host "================= Загрузка прошивки $firmware =================" -ForegroundColor Green
$drive = Wait-ForUSB $firmware
if (-not $drive) { break }
$driveLetter = $drive.DeviceID
Start-Sleep -Seconds 1
# --- Отображение avatar_version.txt ---
$versionFile = Join-Path $driveLetter "avatar_version.txt"
if (Test-Path $versionFile) {
Write-Host "`nСодержимое avatar_version.txt на ${driveLetter}:" -ForegroundColor Yellow
Get-Content $versionFile | ForEach-Object { Write-Host $_ }
} else {
Write-Host "`nФайл прошивки не найден на $driveLetter" -ForegroundColor Red
}
# --- Подтверждение продолжения ---
$continue = Read-Host "`nПродолжить загрузку прошивки? (Y/N)"
if ($continue -notin @('Y', 'y')) {
Write-Host "Ожидание нового подключения..." -ForegroundColor Cyan
Start-Sleep -Seconds 2
continue
}
$targetFile = Join-Path $driveLetter "Avatar_Sky_38.43.$firmware.img"
try {
Write-Host "`nКопирование прошивки на $driveLetter..." -ForegroundColor Cyan
if (-not (Show-Progress $sourceFile $targetFile)) {
throw "Ошибка копирования"
}
Write-Host "`nПроверка контрольной суммы..." -ForegroundColor Cyan
$sourceHash = Get-Checksum $sourceFile
$targetHash = Get-Checksum $targetFile
if ($sourceHash -ne $targetHash) {
throw "Контрольные суммы не совпадают"
}
Write-Host "`nКонтрольные суммы совпадают." -ForegroundColor Green
# --- Извлечение устройства ---
Write-Host "`nИзвлечение устройства..." -NoNewline
if (-not (Safe-Eject $driveLetter)) {
Write-Host "`nПредупреждение: Устройство не извлечено." -ForegroundColor Yellow
} else {
Write-Host "`nУстройство безопасно извлечено." -ForegroundColor Green
}
}
catch {
Write-Host "`nОшибка: $_" -ForegroundColor Red
if (Test-Path $targetFile) {
try { Remove-Item $targetFile -Force }
catch {
Write-Host "Не удалось удалить целевой файл: $_" -ForegroundColor Yellow
}
}
}
finally {
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
Write-Host "`nЗавершено." -ForegroundColor Magenta
Start-Sleep -Seconds 1
}
}
here is bat script for transferring files to usb drive. I need to add third option with this name Avatar_Sky_239.44.2 this file will be in the same directory as 2 other
Below is the modified PowerShell script based on your request. I've added a third option for the firmware version "Avatar_Sky_239.44.2.img". The user input prompt has been updated to include the new option (e.g., "12", "13", or "2 for 239.44.2"). The script now uses a switch statement to handle the different firmware files and their display versions. Additionally, I've made the target file name dynamic by extracting it from the source file path, ensuring it works correctly for all firmware versions.
Here's a summary of the changes:
$version for clarity and updated its usage to pass the display version.Split-Path to get the file name from the source path.Here's the full modified script:
# Set UTF-8 encoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
# --- Admin Elevation ---
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process powershell.exe "-ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
exit
}
# --- Disable Close Button ("X") ---
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
public static extern bool DeleteMenu(IntPtr hMenu, int uPosition, int uFlags);
}
"@
$hwnd = (Get-Process -Id $pid).MainWindowHandle
$menu = [Win32]::GetSystemMenu($hwnd, $false)
[Win32]::DeleteMenu($menu, 0xF060, 0x00000000) | Out-Null # SC_CLOSE
# Disable Ctrl+C and Ctrl+Break termination
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class ConsoleHandler {
public delegate bool HandlerRoutine(int CtrlType);
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
}
"@
$handler = [ConsoleHandler+HandlerRoutine]{
param([int]$ctrlType)
switch ($ctrlType) {
0 { Write-Host "`nНет."; return $true }
1 { Write-Host "`nНет."; return $true }
default { return $false }
}
}
[ConsoleHandler]::SetConsoleCtrlHandler($handler, $true) | Out-Null
# --- Functions ---
function Show-Progress {
param($source, $target)
try {
$file = Get-Item $source -Force
$fileSize = $file.Length
$bufferSize = 1MB
attrib -H -S -R "`"$source`"" | Out-Null
if (Test-Path $target) {
attrib -H -S -R "`"$target`"" | Out-Null
Remove-Item $target -Force
Start-Sleep -Milliseconds 500
}
$inputStream = [System.IO.File]::OpenRead($source)
$outputStream = [System.IO.File]::OpenWrite($target)
$buffer = New-Object byte[] $bufferSize
$totalRead = 0
while ($totalRead -lt $fileSize) {
$bytesRead = $inputStream.Read($buffer, 0, $bufferSize)
$outputStream.Write($buffer, 0, $bytesRead)
$totalRead += $bytesRead
$percent = ($totalRead / $fileSize) * 100
Write-Progress -Activity "Копирование прошивки" -Status "$([Math]::Round($percent,1))% завершено" -PercentComplete $percent
}
$outputStream.Close()
$inputStream.Close()
attrib +H +S +R "`"$source`"" | Out-Null
attrib +H +S +R "`"$target`"" | Out-Null
Write-Progress -Activity "Копирование прошивки" -Completed
return $true
}
catch {
Write-Host "Ошибка копирования: $_" -ForegroundColor Red
return $false
}
}
function Get-Checksum {
param($path)
try {
$originalAttributes = (Get-Item $path -Force).Attributes
(Get-Item $path -Force).Attributes = $originalAttributes -band -bnot [System.IO.FileAttributes]::ReadOnly
return (Get-FileHash $path -Algorithm SHA256 -ErrorAction Stop).Hash
}
finally {
(Get-Item $path -Force).Attributes = $originalAttributes
attrib +H +S +R "`"$path`"" | Out-Null
}
}
function Wait-ForUSB {
param($version)
$spinner = @('|', '/', '-', '\')
$spinnerIndex = 0
while ($true) {
if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
if ($key.Character -eq '-') {
Write-Host "`nПерезапуск скрипта..."
Start-Sleep -Seconds 1
exit 100
}
}
$drive = Get-WmiObject Win32_LogicalDisk |
Where-Object {
$_.DriveType -eq 2 -and
($_.DeviceID.ToUpper() -ne 'Z:') -and
(Test-Path "$($_.DeviceID)\")
} |
Select-Object -First 1
if ($drive) { return $drive }
Write-Host "`r[$($spinner[$spinnerIndex])] Ожидание подключения VTX (прошивка $version)... Нажмите '-' для перезапуска" -NoNewline
$spinnerIndex = ($spinnerIndex + 1) % 4
Start-Sleep -Milliseconds 150
}
}
function Safe-Eject {
param($driveLetter)
try {
Start-Sleep -Seconds 2
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
$shell = New-Object -ComObject Shell.Application
$drive = $shell.Namespace(17).ParseName($driveLetter)
if ($drive) {
$drive.InvokeVerb("Eject")
} else {
throw "Не удалось найти $driveLetter для извлечения"
}
$maxRetries = 30
$retryCount = 0
while ((Test-Path $driveLetter) -and ($retryCount -lt $maxRetries)) {
Start-Sleep -Milliseconds 500
$retryCount++
}
if (Test-Path $driveLetter) {
Write-Host "Устройство не извлечено автоматически. Извлеките вручную." -ForegroundColor Yellow
return $false
}
return $true
}
catch {
Write-Host "Ошибка при извлечении: $_" -ForegroundColor Red
return $false
}
}
# --- Main Loop ---
while ($true) {
cmd /c cls
Write-Host "================= Выбор прошивки =================" -ForegroundColor Cyan
$firmware = Read-Host "`nВыбери версию прошивки? (12, 13 или 2 для 239.44.2)"
while ($firmware -notin '12', '13', '2') {
$firmware = Read-Host "Некорректный ввод. Введите 12, 13 или 2"
}
# Set source file and display version based on input
switch ($firmware) {
'12' { $sourceFile = Join-Path $PSScriptRoot "Firmware\Avatar_Sky_38.43.12.img"; $versionDisplay = "38.43.12" }
'13' { $sourceFile = Join-Path $PSScriptRoot "Firmware\Avatar_Sky_38.43.13.img"; $versionDisplay = "38.43.13" }
'2' { $sourceFile = Join-Path $PSScriptRoot "Firmware\Avatar_Sky_239.44.2.img"; $versionDisplay = "239.44.2" }
}
if (-not (Test-Path $sourceFile)) {
Write-Host "Файл прошивки не найден: $sourceFile" -ForegroundColor Red
Start-Sleep -Seconds 2
continue
}
while ($true) {
cmd /c cls
Write-Host "================= Загрузка прошивки $versionDisplay =================" -ForegroundColor Green
$drive = Wait-ForUSB $versionDisplay
if (-not $drive) { break }
$driveLetter = $drive.DeviceID
Start-Sleep -Seconds 1
# --- Отображение avatar_version.txt ---
$versionFile = Join-Path $driveLetter "avatar_version.txt"
if (Test-Path $versionFile) {
Write-Host "`nСодержимое avatar_version.txt на ${driveLetter}:" -ForegroundColor Yellow
Get-Content $versionFile | ForEach-Object { Write-Host $_ }
} else {
Write-Host "`nФайл прошивки не найден на $driveLetter" -ForegroundColor Red
}
# --- Подтверждение продолжения ---
$continue = Read-Host "`nПродолжить загрузку прошивки? (Y/N)"
if ($continue -notin @('Y', 'y')) {
Write-Host "Ожидание нового подключения..." -ForegroundColor Cyan
Start-Sleep -Seconds 2
continue
}
# Get the file name from the source and set target file
$fileName = Split-Path $sourceFile -Leaf
$targetFile = Join-Path $driveLetter $fileName
try {
Write-Host "`nКопирование прошивки на $driveLetter..." -ForegroundColor Cyan
if (-not (Show-Progress $sourceFile $targetFile)) {
throw "Ошибка копирования"
}
Write-Host "`nПроверка контрольной суммы..." -ForegroundColor Cyan
$sourceHash = Get-Checksum $sourceFile
$targetHash = Get-Checksum $targetFile
if ($sourceHash -ne $targetHash) {
throw "Контрольные суммы не совпадают"
}
Write-Host "`nКонтрольные суммы совпадают." -ForegroundColor Green
# --- Извлечение устройства ---
Write-Host "`nИзвлечение устройства..." -NoNewline
if (-not (Safe-Eject $driveLetter)) {
Write-Host "`nПредупреждение: Устройство не извлечено." -ForegroundColor Yellow
} else {
Write-Host "`nУстройство безопасно извлечено." -ForegroundColor Green
}
}
catch {
Write-Host "`nОшибка: $_" -ForegroundColor Red
if (Test-Path $targetFile) {
try { Remove-Item $targetFile -Force }
catch {
Write-Host "Не удалось удалить целевой файл: $_" -ForegroundColor Yellow
}
}
}
finally {
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
Write-Host "`nЗавершено." -ForegroundColor Magenta
Start-Sleep -Seconds 1
}
}
"$pathAvatar_Sky_239.44.2.img in the Firmware subdirectory relative to the script's location (same as the other firmware files).12 for "Avatar_Sky_38.43.12.img"13 for "Avatar_Sky_38.43.13.img"2 for "Avatar_Sky_239.44.2.img"This modification keeps the script flexible and easy to extend if more firmware options are added in the future. If you have any further adjustments or questions, let me know!