Private/monster_wu.ps1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - WINDOWS UPDATE PAYLOAD (MODULE EDITION)
# Файл: Private\monster_wu.ps1
# Назначение: Управление обновлениями с явным логированием ошибок вместо тихого подавления
# ==============================================================================

[CmdletBinding()]
param(
    [switch]$Check,
    [switch]$Install
)

$isVerbose = $PSBoundParameters['Verbose'] -or ($VerbosePreference -eq 'Continue')

Write-Log -Level "INFO" -Message "Инициализация подсистемы Windows Update..." -Context "WU"

try {
    if (-not (Get-Module -ListAvailable -Name "PSWindowsUpdate")) {
        Write-Log -Level "CRITICAL" -Message "Модуль PSWindowsUpdate не установлен в системе." -Context "WU"
        throw "Модуль PSWindowsUpdate отсутствует."
    }

    if (-not (Get-Module -Name "PSWindowsUpdate" -ErrorAction SilentlyContinue)) {
        Import-Module "PSWindowsUpdate" -ErrorAction Stop
    }
} catch {
    Write-Log -Level "ERROR" -Message "Не удалось загрузить модуль PSWindowsUpdate: $_" -Context "WU"
    exit 1
}

try {
    if ($Check) {
        Write-Log -Level "INFO" -Message "Поиск доступных обновлений Windows..." -Context "WU"

        $updates = Get-WindowsUpdate -ErrorAction Stop

        if ($null -eq $updates -or $updates.Count -eq 0) {
            Write-Log -Level "SUCCESS" -Message "Доступные обновления не обнаружены. Система актуальна." -Context "WU"
            Write-Host "[OK] Обновления не найдены." -ForegroundColor Green
        } else {
            Write-Log -Level "SUCCESS" -Message "Обнаружены доступные обновления ($($updates.Count) шт.)." -Context "WU"
            Write-Host "`nДоступные обновления:" -ForegroundColor Cyan

            $updates | Select-Object `
                @{Name="KB"; Expression={ if ($_.KB) { $_.KB } else { "DEFENDER/OTHER" } }},
                @{Name="Size"; Expression={ if ($_.Size) { "$([Math]::Round($_.Size / 1MB, 2)) MB" } else { "N/A" } }},
                Title | Format-Table -AutoSize
        }
        exit 0
    }

    if ($Install) {
        Write-Log -Level "INFO" -Message "Запуск процесса установки обновлений Windows..." -Context "WU"

        Install-WindowsUpdate -AcceptAll -AutoReboot:$false -Confirm:$false -ErrorAction Stop | Out-Null

        Write-Log -Level "SUCCESS" -Message "Установка обновлений успешно завершена." -Context "WU"
        Write-Host "[OK] Обновления успешно установлены." -ForegroundColor Green
        exit 0
    }

    if (-not $Check -and -not $Install) {
        Write-Log -Level "WARNING" -Message "Не указано действие (-Check или -Install)." -Context "WU"
        Write-Host "Использование: monster_wu.ps1 [-Check] [-Install]" -ForegroundColor Yellow
        exit 1
    }

} catch {
    Write-Log -Level "CRITICAL" -Message "Критическая ошибка в подсистеме Windows Update: $_" -Context "WU"
    exit 1
}