¡Script copiado al portapapeles!

Optimizador Leviatán v8.3

La suite de rendimiento definitiva para limpiar, acelerar, proteger y reparar tu sistema con un poder sin precedentes.

Instrucciones de Uso

  1. Abre una ventana de **Terminal (Administrador)** o **PowerShell (Administrador)**.
  2. Haz clic en el botón de abajo para copiar el script completo.
  3. Vuelve a la terminal, haz clic derecho para pegar el script y presiona **Enter**.
  4. Sigue las instrucciones del menú interactivo que aparecerá en la consola.

Script PowerShell - v8.3 Refactorizado

# =================================================================================================
#
#   PowerScript Optimizador LEVIATÁN v8.3 - Edición Refactorizada
#   Objetivo: Limpieza, aceleración, protección y reparación del sistema a nivel experto.
#
#   ADVERTENCIA: EJECUTAR SIEMPRE COMO ADMINISTRADOR.
#   Este script realiza cambios profundos. Úsese bajo su propia responsabilidad.
#
# =================================================================================================

#region PREPARACIÓN Y CONFIGURACIÓN INICIAL
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Warning "Este script requiere privilegios de Administrador. Por favor, reinicia la terminal como Administrador."
    Start-Sleep -Seconds 10
    Exit
}

function Show-SectionTitle {
    param([string]$Title)
    Write-Host "`n"
    Write-Host "==================================================================" -ForegroundColor Magenta
    Write-Host "    $Title" -ForegroundColor White
    Write-Host "==================================================================" -ForegroundColor Magenta
}

$logFile = "$env:USERPROFILE\Desktop\Optimizador-Leviatan-Log-v8.3.txt"
Function Write-Log {
    param ([string]$Message, [string]$ForegroundColor = 'Gray')
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "[$timestamp] - $Message"
    $logMessage | Out-File -FilePath $logFile -Append
    Write-Host $logMessage -ForegroundColor $foregroundColor
}

Write-Log "Inicio del script Leviatán v8.3."
#endregion

#region CONFIGURACIÓN CENTRALIZADA
$config = @{
    LocationsToClean = @(
        "$env:TEMP\*", "$env:SystemRoot\Temp\*", "$env:SystemRoot\SoftwareDistribution\Download\*",
        "$env:windir\Prefetch\*", "$env:windir\Logs\*", "$env:windir\Panther\*",
        "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Cache\*", 
        "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache\*",
        "$env:LOCALAPPDATA\Discord\Cache\*", "$env:APPDATA\Steam\htmlcache\*",
        "$env:LOCALAPPDATA\NVIDIA\GLCache\*", "$env:LOCALAPPDATA\AMD\DxCache\*",
        "$env:windir\logs\CBS\*", "$env:windir\panther\*", "$env:ProgramData\Microsoft\WER\ReportQueue\*",
        "$env:SystemRoot\System32\Winevt\Logs\*"
    )
    AppsToRemove = @(
        "Microsoft.549981C3F5F10", "*Cortana*", "Microsoft.WindowsSoundRecorder", 
        "Microsoft.Xbox*", "Microsoft.ZuneMusic", "Microsoft.ZuneVideo", "Microsoft.YourPhone", 
        "Microsoft.WindowsAlarms", "Microsoft.WindowsMaps", "Microsoft.SkypeApp", "Microsoft.Getstarted", 
        "Microsoft.GetHelp", "Microsoft.MicrosoftSolitaireCollection", "Microsoft.People", "Microsoft.Office.OneNote", 
        "Microsoft.OneConnect", "Microsoft.Print3D", "Microsoft.Wallet", "Microsoft.MixedReality.Portal", 
        "Microsoft.WindowsFeedbackHub", "Microsoft.BingWeather", "Microsoft.GetOffice", "Microsoft.WindowsCamera"
    )
    ServicesToDisable = @("DiagTrack", "dmwappushservice", "DoSvc")
    UltimatePerformanceGuid = "e9a42b02-d5df-448d-aa00-03f14749eb61"
}
#endregion

#region FUNCIONES CORE
function Create-RestorePoint {
    Show-SectionTitle "Creando Punto de Restauración del Sistema"
    try {
        # Verifica si la restauración del sistema está habilitada antes de proceder
        $srEnabled = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name "DisableSR" -ErrorAction SilentlyContinue).DisableSR -eq 0
        if ($srEnabled) {
            Write-Log "Creando punto de restauración 'Pre-Leviatan-v8.3'..."
            Checkpoint-Computer -Description "Pre-Leviatan-v8.3" -RestorePointType "MODIFY_SETTINGS" -ErrorAction Stop
            Write-Log "Punto de restauración creado con éxito." -ForegroundColor Green
        } else {
            Write-Log "La creación de puntos de restauración está deshabilitada en el sistema. Omitiendo." -ForegroundColor Yellow
        }
    } catch {
        Write-Log "No se pudo crear un nuevo punto de restauración. Motivo: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# --- MÓDULO 1: LIMPIEZA ---
function Invoke-ExhaustiveClean {
    Show-SectionTitle "Limpieza Exhaustiva de Archivos Basura"
    foreach ($location in $config.LocationsToClean) {
        if (Test-Path $location.TrimEnd('*')) {
            Write-Log "Limpiando: $location"
            Remove-Item -Path $location -Recurse -Force -ErrorAction SilentlyContinue
        } else {
            Write-Log "Omitiendo ruta no encontrada: $location" -ForegroundColor DarkGray
        }
    }
    Write-Log "Vaciando registros de eventos, DNS y Papelera..."
    wevtutil el | Where-Object { $_ } | ForEach-Object { wevtutil cl "$_" -ErrorAction SilentlyContinue }
    ipconfig /flushdns | Out-Null
    Clear-RecycleBin -Force -ErrorAction SilentlyContinue
    Write-Log "Limpiando el almacén de componentes de Windows (WinSxS)..."
    Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase | Out-Null
    Write-Log "Limpieza de archivos completada." -ForegroundColor Green
}

function Invoke-RegistryClean {
    Show-SectionTitle "Limpieza del Registro (Función Experimental)"
    Write-Warning "¡PELIGRO! Modificar el registro incorrectamente puede causar inestabilidad."
    $confirmation = Read-Host "¿Estás SEGURO de que deseas continuar? (S/N)"
    if ($confirmation.ToLower() -ne 's') { Write-Log "Operación cancelada." -ForegroundColor Yellow; return }

    Write-Log "Limpiando claves de MRU (Most Recently Used)..."
    Remove-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedPidlMRU\*" -Force -Recurse -ErrorAction SilentlyContinue
    Write-Log "Limpieza del registro finalizada (modo seguro)." -ForegroundColor Green
}

function Invoke-BloatwareRemoval {
    Show-SectionTitle "Depuración Profunda de Windows (Bloatware)"
    if (-not (Get-Command Get-AppxPackage -ErrorAction SilentlyContinue)) {
        Write-Log "Los comandos Appx no están disponibles en esta sesión. Omitiendo." -ForegroundColor Red
        return
    }
    $confirmation = Read-Host "¿Deseas eliminar las apps predefinidas de Windows? (S/N)"
    if ($confirmation.ToLower() -eq 's') {
        foreach ($app in $config.AppsToRemove) {
            Write-Log "Intentando eliminar: $app"
            Get-AppxPackage -AllUsers $app | Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue
            Get-AppxProvisionedPackage -Online | Where-Object { $_.PackageName -like $app } | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue
        }
        Write-Log "Depuración de bloatware completada." -ForegroundColor Green
    } else { Write-Log "Operación de depuración cancelada." -ForegroundColor Yellow }
}

# --- MÓDULO 2: ACELERACIÓN ---
function Invoke-FreeRAM {
    Show-SectionTitle "Liberando Memoria RAM (Limpieza de Standby List)"
    try {
        # Técnica avanzada que fuerza al gestor de memoria a liberar la lista de 'standby'.
        $Code = @"
        using System; using System.Runtime.InteropServices;
        public class MemTool { [DllImport("ntdll.dll")] public static extern int NtSetSystemInformation(int infoClass, IntPtr info, int len); }
"@
        Add-Type -TypeDefinition $Code -ErrorAction Stop
        $ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(4)
        [System.Runtime.InteropServices.Marshal]::WriteInt32($ptr, 2) # SystemPurgeStandbyList
        [MemTool]::NtSetSystemInformation(80, $ptr, 4) # SystemMemoryListInformation
        [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptr)
        Write-Log "Memoria en espera liberada exitosamente." -ForegroundColor Green
    } catch { Write-Log "Error al liberar memoria RAM: $($_.Exception.Message)" -ForegroundColor Red }
}

function Invoke-Defrag {
    Show-SectionTitle "Análisis y Desfragmentación de Disco"
    Write-Log "Analizando estado del disco principal (C:)..."
    defrag.exe C: /A /U /V
    $confirmation = Read-Host "¿Deseas optimizar (desfragmentar) el disco C: ahora? (S/N)"
    if ($confirmation.ToLower() -eq 's') {
        Write-Log "Iniciando optimización. Esto puede tardar."
        defrag.exe C: /O
        Write-Log "Optimización de disco completada." -ForegroundColor Green
    } else { Write-Log "Operación cancelada." -ForegroundColor Yellow }
}

function Invoke-ExtremeOptimization {
    Show-SectionTitle "Aplicando Optimizaciones Extremas Seguras"
    Write-Log "Activando plan 'Máximo Rendimiento'..."
    powercfg -duplicatescheme $config.UltimatePerformanceGuid | Out-Null
    powercfg /s $config.UltimatePerformanceGuid
    Write-Log "'Máximo Rendimiento' activado." -ForegroundColor Green
    
    Write-Log "Desactivando hibernación para liberar espacio..."
    powercfg.exe /hibernate off
    
    Write-Log "Optimizando tiempos de apagado y acceso a archivos..."
    fsutil behavior set disablelastaccess 1
    # Reduce el tiempo de espera para cerrar servicios al apagar.
    Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control" -Name "WaitToKillServiceTimeout" -Value "2000" -ErrorAction SilentlyContinue

    Write-Log "Activando Hardware-Accelerated GPU Scheduling..."
    # Mejora el rendimiento en juegos y apps gráficas.
    Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers" -Name "HwSchMode" -Value 2 -Type Dword -Force -ErrorAction SilentlyContinue
    
    Write-Log "Optimizaciones de red avanzadas..."
    netsh int tcp set global autotuninglevel=normal
    # Elimina el 'throttling' de la red impuesto por Windows.
    Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile" -Name "NetworkThrottlingIndex" -Value 0xFFFFFFFF -Type DWord -Force -ErrorAction SilentlyContinue
    Write-Log "Optimizaciones completadas." -ForegroundColor Green
}

# --- MÓDULO 3: PROTECCIÓN Y PRIVACIDAD ---
function Invoke-SecurityCheck {
    Show-SectionTitle "Revisión de Seguridad de Windows"
    $firewall = Get-NetFirewallProfile | Where-Object {$_.Enabled -eq 'True'}
    if ($firewall) { Write-Log "Firewall de Windows: ACTIVADO." -ForegroundColor Green } else { Write-Log "Firewall de Windows: DESACTIVADO." -ForegroundColor Red }
    
    $av = Get-MpComputerStatus
    if ($av.AntivirusEnabled) { Write-Log "Microsoft Defender: ACTIVADO." -ForegroundColor Green } else { Write-Log "Microsoft Defender: DESACTIVADO." -ForegroundColor Red }
}

function Invoke-PrivacyShield {
    Show-SectionTitle "Escudo de Privacidad (Anti-Telemetría)"
    Write-Log "Desactivando servicios de telemetría y recolección de datos..."
    foreach ($service in $config.ServicesToDisable) {
        if (Get-Service -Name $service -ErrorAction SilentlyContinue) {
            Write-Log "Desactivando servicio: $service"
            Set-Service -Name $service -StartupType Disabled -Status Stopped -ErrorAction SilentlyContinue
        }
    }
    Set-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection" -Name "AllowTelemetry" -Value 0 -Type DWord -Force -ErrorAction SilentlyContinue
    Write-Log "Escudo de privacidad activado." -ForegroundColor Green
}

function Invoke-UniversalUpdate {
    Show-SectionTitle "Buscando Actualizaciones (Sistema y Apps)"
    Write-Log "Fase 1: Actualizando Windows..."
    try {
        Install-Module -Name PSWindowsUpdate -Force -AcceptLicense -Scope CurrentUser -ErrorAction Stop | Out-Null
        Import-Module PSWindowsUpdate -ErrorAction Stop
        Get-WindowsUpdate -AcceptAll -Install -AutoReboot
        Write-Log "Sistema Operativo Windows actualizado." -ForegroundColor Green
    } catch {
        Write-Log "No se pudo completar la actualización de Windows. Puede que el módulo PSWindowsUpdate no se instalara correctamente." -ForegroundColor Red
    }
    
    Write-Log "Fase 2: Actualizando aplicaciones con Winget..."
    if (Get-Command "winget" -ErrorAction SilentlyContinue) {
        winget upgrade --all --accept-package-agreements --accept-source-agreements --disable-interactivity
        Write-Log "Aplicaciones de Winget actualizadas." -ForegroundColor Green
    } else { Write-Log "Winget no encontrado. Omitiendo." -ForegroundColor Yellow }
}

# --- MÓDULO 4: REPARACIÓN ---
function Invoke-SystemRepair {
    Show-SectionTitle "Reparación Integral del Sistema"
    Write-Log "Verificando y reparando integridad de archivos (SFC)..."
    sfc /scannow
    Write-Log "Verificando y reparando imagen de componentes (DISM)..."
    Dism /Online /Cleanup-Image /RestoreHealth
    Write-Log "Mantenimiento completado." -ForegroundColor Green
}

function Invoke-NetworkRepair {
    Show-SectionTitle "Reparación de Conexión de Red"
    Write-Warning "Esto reiniciará tus adaptadores de red."
    $confirmation = Read-Host "¿Estás seguro de que deseas continuar? (S/N)"
    if ($confirmation.ToLower() -ne 's') { Write-Log "Operación cancelada." -ForegroundColor Yellow; return }

    ipconfig /release; ipconfig /renew; ipconfig /flushdns
    nbtstat -R; nbtstat -RR
    netsh int ip reset all
    netsh winsock reset
    Write-Log "La reparación de red ha finalizado. Se recomienda reiniciar." -ForegroundColor Green
}

function Invoke-DiskCheck {
    Show-SectionTitle "Reparación de Errores de Disco (CHKDSK)"
    Write-Warning "Esta operación requiere un REINICIO para escanear el disco del sistema."
    $confirmation = Read-Host "¿Programar un CHKDSK en el próximo reinicio? (S/N)"
    if ($confirmation.ToLower() -eq 's') {
        chkdsk C: /f /r
        Write-Log "CHKDSK programado. Reinicia tu PC para comenzar." -ForegroundColor Green
    } else { Write-Log "Operación cancelada." -ForegroundColor Yellow }
}

# --- MÓDULO 5: DIAGNÓSTICO ---
function Show-DiagnosticsMenu {
    Show-SectionTitle "Realizando Diagnóstico Avanzado del Sistema"
    $reportPath = "$env:USERPROFILE\Desktop\Diagnostico-Leviatan.txt"
    "Reporte de Diagnóstico - $(Get-Date)" | Out-File -FilePath $reportPath
    (systeminfo) | Out-File -FilePath $reportPath -Append
    ("`n--- Top 10 Procesos por CPU ---`n") | Out-File -FilePath $reportPath -Append
    (Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 | Format-Table | Out-String) | Out-File -FilePath $reportPath -Append
    ("`n--- Top 10 Procesos por RAM (WS) ---`n") | Out-File -FilePath $reportPath -Append
    (Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 10 | Format-Table | Out-String) | Out-File -FilePath $reportPath -Append
    Write-Log "Diagnóstico completado. Revisa el archivo en tu escritorio." -ForegroundColor Green
    Invoke-Item $reportPath
}
#endregion

#region MENUS
function Show-MenuTemplate {
    param(
        [string]$Title,
        [System.Collections.IDictionary]$MenuItems,
        [scriptblock]$AllAction
    )
    do {
        Clear-Host
        Write-Host "--- $Title ---" -ForegroundColor Cyan
        foreach ($key in $MenuItems.Keys | Sort-Object) {
            Write-Host "   [$key] $($MenuItems[$key])"
        }
        Write-Host "   [A] Ejecutar TODO en esta categoría"
        Write-Host "   [B] Volver al Menú Principal"
        $choice = Read-Host "Selecciona una opción"
        if ($MenuItems.ContainsKey($choice)) {
            . $(Get-Command $MenuItems[$choice].Split(' ')[0])
        } elseif ($choice.ToLower() -eq 'a') {
            & $AllAction
        } elseif ($choice.ToLower() -eq 'b') {
            break
        } else {
            Write-Host "Opción no válida." -ForegroundColor Yellow; Start-Sleep -Seconds 1
        }
        if ($MenuItems.ContainsKey($choice) -or $choice.ToLower() -eq 'a') { Write-Host "`nOperación completada. Presiona Enter..."; Read-Host | Out-Null }
    } while ($true)
}

function Show-MainMenu {
    Clear-Host
    Write-Host "╔════════════════════════════════════════════════════════════════════╗" -ForegroundColor Magenta
    Write-Host "║        🐲 OPTIMIZADOR LEVIATÁN v8.3 - Edición Refactorizada 🐲     ║" -ForegroundColor White
    Write-Host "╚════════════════════════════════════════════════════════════════════╝" -ForegroundColor Magenta
    Write-Host "`nADVERTENCIA: Herramienta de poder extremo. Proceda con precaución." -ForegroundColor Red
    Write-Host "`nSelecciona una categoría:" -ForegroundColor Magenta
    Write-Host "   [1] Limpieza Profunda"
    Write-Host "   [2] Aceleración del Sistema"
    Write-Host "   [3] Protección y Privacidad"
    Write-Host "   [4] Reparación del Sistema"
    Write-Host "   [5] Diagnóstico del Sistema"
    Write-Host "   [A] ¡MODO APOCALIPSIS! (Ejecuta las optimizaciones más seguras)"
    Write-Host "   [R] Crear Punto de Restauración"
    Write-Host "   [Q] Salir"
}
#endregion

#region BUCLE PRINCIPAL
do {
    Show-MainMenu
    $option = (Read-Host "`nTu elección").ToLower()
    switch ($option) {
        "1" { Show-MenuTemplate -Title "Menú de Limpieza" -MenuItems @{
                '1' = 'Invoke-ExhaustiveClean'; 
                '2' = 'Invoke-RegistryClean'; 
                '3' = 'Invoke-BloatwareRemoval'} -AllAction { Invoke-ExhaustiveClean; Invoke-RegistryClean; Invoke-BloatwareRemoval } }
        "2" { Show-MenuTemplate -Title "Menú de Aceleración" -MenuItems @{
                '1' = 'Invoke-FreeRAM'; 
                '2' = 'Invoke-Defrag'; 
                '3' = 'Invoke-ExtremeOptimization'} -AllAction { Invoke-FreeRAM; Invoke-Defrag; Invoke-ExtremeOptimization } }
        "3" { Show-MenuTemplate -Title "Menú de Protección" -MenuItems @{
                '1' = 'Invoke-SecurityCheck'; 
                '2' = 'Invoke-PrivacyShield'; 
                '3' = 'Invoke-UniversalUpdate'} -AllAction { Invoke-SecurityCheck; Invoke-PrivacyShield; Invoke-UniversalUpdate } }
        "4" { Show-MenuTemplate -Title "Menú de Reparación" -MenuItems @{
                '1' = 'Invoke-SystemRepair'; 
                '2' = 'Invoke-NetworkRepair'; 
                '3' = 'Invoke-DiskCheck'} -AllAction { Invoke-SystemRepair; Invoke-NetworkRepair; Invoke-DiskCheck } }
        "5" { Show-DiagnosticsMenu }
        "a" { 
            Create-RestorePoint
            Invoke-ExhaustiveClean
            Invoke-BloatwareRemoval
            Invoke-ExtremeOptimization
            Invoke-PrivacyShield
            Invoke-SystemRepair
            Invoke-FreeRAM
            Write-Host "`n¡MODO APOCALIPSIS COMPLETADO! Se recomienda reiniciar." -ForegroundColor Magenta
        }
        "r" { Create-RestorePoint }
        "q" { Write-Log "Saliendo del Optimizador Leviatán."; Write-Host "Saliendo..." -ForegroundColor Green }
        default { Write-Host "Opción no válida." -ForegroundColor Yellow; Start-Sleep -Seconds 1 }
    }
    if ($option -in '5', 'a', 'r') {
        Write-Host "`nOperación completada. Presiona Enter para volver al menú..."
        Read-Host | Out-Null
    }
} while ($option -ne 'q')
#endregion