Private/monster_optimizer.ps1
|
# ============================================================================== # MONSTER SCRIPT ENTERPRISE - OPTIMIZER PAYLOAD (MODULE EDITION) # Файл: Private\monster_optimizer.ps1 # Назначение: Оптимизация сети и кэша с поддержкой мультиязычной локализации # ============================================================================== [CmdletBinding()] param( [switch]$OptimizeNetwork, [switch]$FlushDNS, [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' } 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 'OPTIMIZER' 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_optimizer' ` -Language $Language } catch { Write-Log ` -Level 'WARNING' ` -Message "Не удалось загрузить локализацию: $($_.Exception.Message)" ` -Context 'OPTIMIZER' } } # ------------------------------------------------------------------------------ # Локализованные сообщения с fallback-текстами # ------------------------------------------------------------------------------ $txtInit = if ($msg.InitOptimizer) { $msg.InitOptimizer } else { 'Инициализация модуля оптимизации...' } $txtFlushStart = if ($msg.FlushDnsStart) { $msg.FlushDnsStart } else { 'Сброс кэша DNS через ipconfig...' } $txtFlushDone = if ($msg.FlushDnsSuccess) { $msg.FlushDnsSuccess } else { 'Кэш DNS успешно сброшен.' } $txtFlushHost = if ($msg.OkFlushDns) { $msg.OkFlushDns } else { '[OK] Кэш DNS очищен.' } $txtOptStart = if ($msg.OptNetStart) { $msg.OptNetStart } else { 'Применение сетевых оптимизаций (TCP/IP)...' } $txtOptDone = if ($msg.OptNetSuccess) { $msg.OptNetSuccess } else { 'Сетевые параметры оптимизированы.' } $txtOptHost = if ($msg.OkOptNet) { $msg.OkOptNet } else { '[OK] Сетевые параметры оптимизированы.' } $txtNoParams = if ($msg.NoParamsWarn) { $msg.NoParamsWarn } else { 'Не указаны параметры оптимизации (-OptimizeNetwork или -FlushDNS).' } $txtUsage = if ($msg.UsageInfo) { $msg.UsageInfo } else { 'Использование: monster_optimizer.ps1 [-OptimizeNetwork] [-FlushDNS] [-Language ru|ua|en]' } $txtCritError = if ($msg.CritError) { $msg.CritError } else { 'Критическая ошибка в модуле оптимизации: {0}' } # ------------------------------------------------------------------------------ # Основная логика # ------------------------------------------------------------------------------ Write-Log ` -Level 'INFO' ` -Message $txtInit ` -Context 'OPTIMIZER' try { # -------------------------------------------------------------------------- # Сброс DNS-кэша # -------------------------------------------------------------------------- if ($FlushDNS) { Write-Log ` -Level 'INFO' ` -Message $txtFlushStart ` -Context 'OPTIMIZER' $output = & ipconfig.exe /flushdns 2>&1 $flushExitCode = $LASTEXITCODE if ($flushExitCode -eq 0) { Write-Log ` -Level 'SUCCESS' ` -Message $txtFlushDone ` -Context 'OPTIMIZER' Write-Host ` $txtFlushHost ` -ForegroundColor Green } else { $errFmt = if ($msg.FlushDnsError) { $msg.FlushDnsError } else { 'ipconfig /flushdns завершился с кодом ошибки {0}. Вывод: {1}' } throw ( $errFmt -f $flushExitCode, ($output -join '; ') ) } } # -------------------------------------------------------------------------- # Оптимизация сетевых параметров # -------------------------------------------------------------------------- if ($OptimizeNetwork) { Write-Log ` -Level 'INFO' ` -Message $txtOptStart ` -Context 'OPTIMIZER' Set-NetIPInterface ` -InterfaceMetric 10 ` -ErrorAction SilentlyContinue Write-Log ` -Level 'SUCCESS' ` -Message $txtOptDone ` -Context 'OPTIMIZER' Write-Host ` $txtOptHost ` -ForegroundColor Green } # -------------------------------------------------------------------------- # Отсутствие параметров # -------------------------------------------------------------------------- if (-not $OptimizeNetwork -and -not $FlushDNS) { Write-Log ` -Level 'WARNING' ` -Message $txtNoParams ` -Context 'OPTIMIZER' Write-Host ` $txtUsage ` -ForegroundColor Yellow } exit 0 } catch { $criticalMessage = if ($msg.CritError) { $msg.CritError -f $_.Exception.Message } else { $txtCritError -f $_.Exception.Message } Write-Log ` -Level 'CRITICAL' ` -Message $criticalMessage ` -Context 'OPTIMIZER' exit 1 } |