Private/monster_usb.ps1
|
# ============================================================================== # MONSTER SCRIPT ENTERPRISE - USB RESET PAYLOAD (MODULE EDITION) # Файл: Private\monster_usb.ps1 # Назначение: Сброс USB Host-контроллеров с поддержкой мультиязычной локализации # ============================================================================== [CmdletBinding()] param( [Parameter(Mandatory = $false)] [ValidatePattern('^[a-zA-Z]{2}(-[a-zA-Z]{2,4})?$')] [string]$Language ) # ------------------------------------------------------------------------------ # Автономный fallback для Write-Log # ------------------------------------------------------------------------------ if (-not (Get-Command -Name Write-Log -ErrorAction SilentlyContinue)) { function Write-Log { param( [Parameter(Mandatory = $true)] [string]$Level, [Parameter(Mandatory = $true)] [string]$Message, [string]$Context = 'GENERAL' ) $timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') $color = switch ($Level.ToUpperInvariant()) { 'SUCCESS' { 'Green' } 'WARNING' { 'Yellow' } 'ERROR' { 'Red' } 'CRITICAL' { 'DarkRed' } 'VERBOSE' { 'Magenta' } 'DEBUG' { 'DarkGray' } default { 'Cyan' } } Write-Host ` "[$timestamp] [$Level] [$Context] $Message" ` -ForegroundColor $color } } # ------------------------------------------------------------------------------ # Определение директории скрипта # ------------------------------------------------------------------------------ $scriptDir = $PSScriptRoot if (-not $scriptDir -and $MyInvocation.MyCommand.Path) { $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path } if (-not $scriptDir) { $scriptDir = (Get-Location).Path } # ------------------------------------------------------------------------------ # Подключение MonsterCore # ------------------------------------------------------------------------------ $coreModulePath = Join-Path ` -Path (Split-Path -Parent $scriptDir) ` -ChildPath 'Private\MonsterCore.psm1' if (-not (Test-Path -LiteralPath $coreModulePath -PathType Leaf)) { $coreModulePath = Join-Path ` -Path $scriptDir ` -ChildPath 'MonsterCore.psm1' } if (-not (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue)) { if (Test-Path -LiteralPath $coreModulePath -PathType Leaf) { try { Import-Module ` -Name $coreModulePath ` -Force ` -ErrorAction Stop } catch { Write-Log ` -Level 'ERROR' ` -Message "Не удалось загрузить MonsterCore: $($_.Exception.Message)" ` -Context 'USB' exit 1 } } } # ------------------------------------------------------------------------------ # Установка языка # ------------------------------------------------------------------------------ if ( $Language -and (Get-Command -Name Set-MonsterLanguage -ErrorAction SilentlyContinue) ) { Set-MonsterLanguage -Language $Language } # ------------------------------------------------------------------------------ # Загрузка локализации # ------------------------------------------------------------------------------ $msg = @{} if (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue) { try { $msg = Get-MonsterLocalization ` -ComponentName 'monster_usb' ` -Language $Language } catch { Write-Log ` -Level 'WARNING' ` -Message "Не удалось загрузить локализацию: $($_.Exception.Message)" ` -Context 'USB' } } # ------------------------------------------------------------------------------ # Локализованные сообщения с fallback-текстами # ------------------------------------------------------------------------------ $txtInit = if ($msg.InitUSB) { $msg.InitUSB } else { 'Инициализация экстренного сброса USB-контроллеров...' } $txtModuleErr = if ($msg.ModuleError) { $msg.ModuleError } else { 'Не удалось загрузить модуль PnpDevice: {0}' } $txtSearch = if ($msg.SearchUSB) { $msg.SearchUSB } else { 'Поиск и перезагрузка USB Host-контроллеров через PnpDevice...' } $txtNotFound = if ($msg.NotFound) { $msg.NotFound } else { 'USB-контроллеры не найдены через фильтр PnpDevice.' } $txtSuccess = if ($msg.SuccessDone) { $msg.SuccessDone } else { 'Процедура сброса USB-контроллеров завершена.' } $txtCritError = if ($msg.CritError) { $msg.CritError } else { 'Критическая ошибка при сбросе USB-контроллеров: {0}' } $isVerbose = ( $PSBoundParameters.ContainsKey('Verbose') -or $VerbosePreference -eq 'Continue' ) Write-Log ` -Level 'INFO' ` -Message $txtInit ` -Context 'USB' # ------------------------------------------------------------------------------ # Загрузка модуля PnpDevice # ------------------------------------------------------------------------------ try { if (-not (Get-Module -Name PnpDevice -ErrorAction SilentlyContinue)) { Import-Module ` -Name PnpDevice ` -ErrorAction Stop } } catch { $moduleErrorMessage = if ($msg.ModuleError) { $msg.ModuleError -f $_.Exception.Message } else { $txtModuleErr -f $_.Exception.Message } Write-Log ` -Level 'ERROR' ` -Message $moduleErrorMessage ` -Context 'USB' exit 1 } # ------------------------------------------------------------------------------ # Основная логика сброса USB-контроллеров # ------------------------------------------------------------------------------ try { Write-Log ` -Level 'INFO' ` -Message $txtSearch ` -Context 'USB' $usbControllers = @( Get-PnpDevice ` -Class 'USB' ` -ErrorAction Stop | Where-Object { $_.FriendlyName -like '*Host Controller*' -or $_.FriendlyName -like '*XHCI*' -or $_.FriendlyName -like '*USB Root Hub*' } ) if ($usbControllers.Count -eq 0) { Write-Log ` -Level 'WARNING' ` -Message $txtNotFound ` -Context 'USB' } else { foreach ($controller in $usbControllers) { $devName = if ( -not [string]::IsNullOrWhiteSpace($controller.FriendlyName) ) { $controller.FriendlyName } else { 'Unknown USB Device' } if ($isVerbose) { $verbMsg = if ($msg.VerboseRestart) { $msg.VerboseRestart -f $devName } else { "Перезагрузка устройства: $devName" } Write-Log ` -Level 'VERBOSE' ` -Message $verbMsg ` -Context 'USB' } try { if ( [string]::IsNullOrWhiteSpace( $controller.InstanceId ) ) { throw 'У USB-устройства отсутствует InstanceId.' } Disable-PnpDevice ` -InstanceId $controller.InstanceId ` -Confirm:$false ` -ErrorAction Stop Start-Sleep -Seconds 1 Enable-PnpDevice ` -InstanceId $controller.InstanceId ` -Confirm:$false ` -ErrorAction Stop } catch { $deviceErrorMessage = if ($msg.DeviceError) { $msg.DeviceError -f $devName } else { "Ошибка при переключении устройства [$devName]:" } Write-Log ` -Level 'ERROR' ` -Message "$deviceErrorMessage $($_.Exception.Message)" ` -Context 'USB' } } } Write-Log ` -Level 'SUCCESS' ` -Message $txtSuccess ` -Context 'USB' exit 0 } catch { $criticalMessage = if ($msg.CritError) { $msg.CritError -f $_.Exception.Message } else { $txtCritError -f $_.Exception.Message } Write-Log ` -Level 'CRITICAL' ` -Message $criticalMessage ` -Context 'USB' exit 1 } |