Private/task_manager.ps1
|
# ============================================================================== # MONSTER SCRIPT ENTERPRISE - TASK MANAGER PAYLOAD (SCHTASKS EDITION) # Файл: Private\task_manager.ps1 # Назначение: Управление планировщиком задач с явным логированием ошибок # ============================================================================== [CmdletBinding()] param( [switch]$Install, [switch]$Remove, [switch]$Check, [switch]$Fix ) $isVerbose = $PSBoundParameters['Verbose'] -or ($VerbosePreference -eq 'Continue') Write-Log -Level "INFO" -Message "Старт менеджера планировщика задач (модульный режим)..." -Context "MANAGER" $scriptDir = $PSScriptRoot if (-not $scriptDir -and $MyInvocation.MyCommand.Path) { $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path } if (-not $scriptDir) { $scriptDir = (Get-Location).Path } $coreModulePath = Join-Path $scriptDir "MonsterCore.psm1" if (-not (Get-Module -Name "MonsterCore" -ErrorAction SilentlyContinue)) { if (Test-Path $coreModulePath) { Import-Module $coreModulePath -Force -ErrorAction Stop } else { Write-Log -Level "ERROR" -Message "Не найден модуль ядра MonsterCore по пути: $coreModulePath" -Context "MANAGER" } } $tasksConfig = @( @{ Name = "MonsterMaintenanceAuto" Description = "MonsterScript Enterprise - Автоматическое обслуживание системы по расписанию." Action = "Invoke-MonsterMaintenance" Argument = "-Auto" }, @{ Name = "MonsterMaintenancePermanent" Description = "MonsterScript Enterprise - Постоянная задача очистки под TrustedInstaller." Action = "Invoke-MonsterMaintenance" Argument = "-ExecuteCleanup" }, @{ Name = "MonsterRepairApps" Description = "MonsterScript Enterprise - Восстановление UWP/AppX пакетов." Action = "Invoke-MonsterMaintenance" Argument = "-RepairApps" } ) try { if ($Check) { Write-Log -Level "INFO" -Message "Проверка статуса задач в Планировщике..." -Context "MANAGER" foreach ($cfg in $tasksConfig) { $tName = $cfg.Name $queryOutput = & schtasks.exe /query /tn $tName 2>&1 if ($LASTEXITCODE -eq 0) { Write-Host " [OK] Задача найдена: $tName" -ForegroundColor Green Write-Log -Level "SUCCESS" -Message "Задача [$tName] присутствует в планировщике." -Context "MANAGER" } else { Write-Host " [!] Задача НЕ НАЙДЕНА: $tName" -ForegroundColor Yellow Write-Log -Level "WARNING" -Message "Задача [$tName] отсутствует в планировщике. Детали запроса: $($queryOutput -join '; ')" -Context "MANAGER" } } exit 0 } if ($Install) { Write-Log -Level "INFO" -Message "Регистрация задач в Планировщике Windows..." -Context "MANAGER" foreach ($cfg in $tasksConfig) { $tName = $cfg.Name try { $commandLine = "powershell.exe -NoProfile -WindowStyle Hidden -Command Import-Module MonsterScript; $($cfg.Action) $($cfg.Argument)" $createOutput = & schtasks.exe /create /tn $tName /tr $commandLine /sc ONSTART /ru "NT AUTHORITY\SYSTEM" /rl HIGHEST /f 2>&1 if ($LASTEXITCODE -eq 0) { Write-Log -Level "SUCCESS" -Message "Задача [$tName] успешно зарегистрирована." -Context "MANAGER" Write-Host "[OK] Зарегистрирована задача: $tName" -ForegroundColor Green } else { throw "schtasks завершился с кодом ошибки $LASTEXITCODE. Вывод: $($createOutput -join '; ')" } } catch { Write-Log -Level "ERROR" -Message "Не удалось зарегистрировать задачу [$tName]: $_" -Context "MANAGER" } } exit 0 } if ($Remove) { Write-Log -Level "INFO" -Message "Удаление задач из Планировщика Windows..." -Context "MANAGER" foreach ($cfg in $tasksConfig) { $tName = $cfg.Name try { $deleteOutput = & schtasks.exe /delete /tn $tName /f 2>&1 if ($LASTEXITCODE -eq 0) { Write-Log -Level "SUCCESS" -Message "Задача [$tName] удалена." -Context "MANAGER" Write-Host "[OK] Удалена задача: $tName" -ForegroundColor Green } else { Write-Log -Level "WARNING" -Message "Задача [$tName] не найдена при попытке удаления или уже отсутствует." -Context "MANAGER" } } catch { Write-Log -Level "ERROR" -Message "Ошибка при удалении задачи [$tName]: $_" -Context "MANAGER" } } exit 0 } if ($Fix) { Write-Log -Level "INFO" -Message "Запуск процедуры исправления и перерегистрации задач..." -Context "MANAGER" & $MyInvocation.MyCommand.Path -Remove & $MyInvocation.MyCommand.Path -Install exit 0 } } catch { Write-Log -Level "CRITICAL" -Message "Критическая ошибка в менеджере задач: $_" -Context "MANAGER" exit 1 } |