# ===================================================================== # Optimiza v0.2 - https://optimizacion.civicloud.es # Analiza tu PC, aplica ajustes reversibles por niveles y mide el antes/despues. # Dos perfiles: USO DIARIO (trabajo, estudios, casa) y GAMER. # Uso (Terminal como administrador): # irm https://optimizacion.civicloud.es/run/ | iex # Todo lo que cambia se guarda en %LOCALAPPDATA%\Optimiza\backup.json # y se puede deshacer desde el menu. # ===================================================================== function Start-Optimiza { $Version = '0.2.0' $Base = 'https://optimizacion.civicloud.es' $Dir = Join-Path $env:LOCALAPPDATA 'Optimiza' $BackupFile = Join-Path $Dir 'backup.json' $StateFile = Join-Path $Dir 'state.json' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 New-Item -ItemType Directory -Force -Path $Dir | Out-Null $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host '' Write-Host ' Necesito permisos de administrador.' -ForegroundColor Red Write-Host ' Clic derecho en el boton de Inicio > "Terminal (Administrador)" y vuelve a pegar el comando.' return } # ================================================================ utilidades function Get-Reg([string]$Path, [string]$Name) { try { return (Get-ItemProperty -Path $Path -Name $Name -ErrorAction Stop).$Name } catch { return $null } } function Set-Reg([string]$Path, [string]$Name, $Value, [string]$Type) { if (-not (Test-Path $Path)) { New-Item -Path $Path -Force | Out-Null } if ($Type -eq 'Binary') { $Value = [byte[]]@($Value) } New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $Type -Force | Out-Null } function Read-Json([string]$File) { $h = @{} if (Test-Path $File) { try { $o = Get-Content $File -Raw -Encoding UTF8 | ConvertFrom-Json foreach ($p in $o.PSObject.Properties) { $h[$p.Name] = $p.Value } } catch { } } return $h } function Save-Json($Hash, [string]$File) { ($Hash | ConvertTo-Json -Depth 8) | Set-Content -Path $File -Encoding UTF8 } function Ask([string]$Text) { $r = Read-Host "$Text [s/n]"; return ($r -match '^(s|si|y|yes)$') } function Line { Write-Host ('-' * 64) -ForegroundColor DarkGray } function Backup-Value($Bk, [string]$Path, [string]$Name, [string]$Type) { $key = "$Path|$Name" if (-not $Bk.ContainsKey($key)) { $old = Get-Reg $Path $Name if ($old -is [byte[]]) { $old = @($old | ForEach-Object { [int]$_ }) } $Bk[$key] = [ordered]@{ path = $Path; name = $Name; old = $old; type = $Type } } } # ================================================================ rutas y ajustes $K = @{ GameBar = 'HKCU:\Software\Microsoft\GameBar' Dvr = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\GameDVR' Gfx = 'HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers' Mouse = 'HKCU:\Control Panel\Mouse' MM = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile' CDM = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager' ExplPol = 'HKCU:\Software\Policies\Microsoft\Windows\Explorer' Search = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Search' Storage = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy' WinMet = 'HKCU:\Control Panel\Desktop\WindowMetrics' Desktop = 'HKCU:\Control Panel\Desktop' ExplAdv = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' AdInfo = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo' DataCol = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection' } $HighPerf = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' $Tweaks = @( # ---------- GAMER @{ Id='gamemode'; Perfil='gamer'; Nivel='leve'; Nombre='Activar el Modo de juego'; Desc='Windows prioriza el juego y no instala drivers ni muestra avisos mientras juegas.'; Reg=@( @{P=$K.GameBar; N='AutoGameModeEnabled'; V=1; T='DWord'}, @{P=$K.GameBar; N='AllowAutoGameMode'; V=1; T='DWord'} ) }, @{ Id='dvr'; Perfil='gamer'; Nivel='leve'; Nombre='Sin grabacion en segundo plano (Game Bar)'; Desc='Deja de grabar continuamente los ultimos minutos de juego, que consume GPU y disco.'; Reg=@( @{P=$K.Dvr; N='HistoricalCaptureEnabled'; V=0; T='DWord'} ) }, @{ Id='power'; Perfil='gamer'; Nivel='leve'; Nombre='Energia: maximo rendimiento'; Desc='Evita que Windows baje la frecuencia del procesador mientras juegas.'; Reg=@() }, @{ Id='hags'; Perfil='gamer'; Nivel='moderado'; Nombre='Programacion de GPU acelerada por hardware'; Desc='La grafica gestiona su propia memoria. Necesita reiniciar. Mide antes y despues.'; Reg=@( @{P=$K.Gfx; N='HwSchMode'; V=2; T='DWord'} ) }, @{ Id='mouse'; Perfil='gamer'; Nivel='moderado'; Nombre='Quitar la aceleracion del raton'; Desc='El raton se mueve siempre igual: mejor punteria. Se aplica al volver a iniciar sesion.'; Reg=@( @{P=$K.Mouse; N='MouseSpeed'; V='0'; T='String'}, @{P=$K.Mouse; N='MouseThreshold1'; V='0'; T='String'}, @{P=$K.Mouse; N='MouseThreshold2'; V='0'; T='String'} ) }, @{ Id='multimedia'; Perfil='gamer'; Nivel='moderado'; Nombre='Prioridad multimedia para juegos'; Desc='Reserva menos CPU a tareas de fondo y quita el limitador de red del programador multimedia.'; Reg=@( @{P=$K.MM; N='SystemResponsiveness'; V=10; T='DWord'}, @{P=$K.MM; N='NetworkThrottlingIndex'; V=([int]-1); T='DWord'} ) }, # ---------- USO DIARIO @{ Id='ads'; Perfil='usuario'; Nivel='leve'; Nombre='Quitar anuncios y sugerencias de Windows'; Desc='Sin apps patrocinadas que se instalan solas ni "sugerencias" en Inicio y Configuracion.'; Reg=@( @{P=$K.CDM; N='SubscribedContent-338388Enabled'; V=0; T='DWord'}, @{P=$K.CDM; N='SubscribedContent-338389Enabled'; V=0; T='DWord'}, @{P=$K.CDM; N='SubscribedContent-353694Enabled'; V=0; T='DWord'}, @{P=$K.CDM; N='SubscribedContent-353696Enabled'; V=0; T='DWord'}, @{P=$K.CDM; N='SystemPaneSuggestionsEnabled'; V=0; T='DWord'}, @{P=$K.CDM; N='SilentInstalledAppsEnabled'; V=0; T='DWord'} ) }, @{ Id='bing'; Perfil='usuario'; Nivel='leve'; Nombre='Busqueda del menu Inicio solo en tu PC'; Desc='El buscador de Inicio deja de mandar lo que escribes a Bing: busca mas rapido y solo en tu equipo.'; Reg=@( @{P=$K.ExplPol; N='DisableSearchBoxSuggestions'; V=1; T='DWord'}, @{P=$K.Search; N='BingSearchEnabled'; V=0; T='DWord'} ) }, @{ Id='storagesense'; Perfil='usuario'; Nivel='leve'; Nombre='Activar el Sensor de almacenamiento'; Desc='Windows vacia solo la papelera y los temporales antiguos para que no se llene el disco.'; Reg=@( @{P=$K.Storage; N='01'; V=1; T='DWord'} ) }, @{ Id='animations'; Perfil='usuario'; Nivel='moderado'; Nombre='Menos animaciones, menus mas rapidos'; Desc='Quita animaciones de ventanas y barra de tareas y acelera los menus. Se nota en PCs modestos.'; Reg=@( @{P=$K.WinMet; N='MinAnimate'; V='0'; T='String'}, @{P=$K.ExplAdv; N='TaskbarAnimations'; V=0; T='DWord'}, @{P=$K.Desktop; N='MenuShowDelay'; V='100'; T='String'} ) }, @{ Id='adid'; Perfil='usuario'; Nivel='moderado'; Nombre='Desactivar el ID de publicidad'; Desc='Las apps dejan de usar un identificador para mostrarte anuncios personalizados.'; Reg=@( @{P=$K.AdInfo; N='Enabled'; V=0; T='DWord'} ) }, @{ Id='telemetry'; Perfil='usuario'; Nivel='moderado'; Nombre='Telemetria al minimo permitido'; Desc='Windows envia solo los datos de diagnostico obligatorios. (En PCs de empresa, puede mandarlo la politica de IT.)'; Reg=@( @{P=$K.DataCol; N='AllowTelemetry'; V=1; T='DWord'} ) } ) # ================================================================ sistema function Get-PowerPlan { $out = (powercfg /getactivescheme) 2>$null | Out-String $g = ''; $n = '' if ($out -match '([0-9a-fA-F\-]{36})') { $g = $Matches[1] } if ($out -match '\((.+)\)') { $n = $Matches[1] } return @{ Guid = $g; Name = $n } } function Test-ModernStandby { $a = (powercfg /a) 2>$null | Out-String; return ($a -match 'S0') } function Get-StartupItems { $items = New-Object System.Collections.ArrayList $sets = @( @{ Run='HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'; Appr='HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'; Scope='Usuario' }, @{ Run='HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'; Appr='HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'; Scope='Equipo' }, @{ Run='HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; Appr='HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32'; Scope='Equipo (32 bits)' } ) foreach ($s in $sets) { if (-not (Test-Path $s.Run)) { continue } $gi = Get-ItemProperty $s.Run -ErrorAction SilentlyContinue if (-not $gi) { continue } $props = $gi.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS(Path|ParentPath|ChildName|Drive|Provider)$' } foreach ($p in $props) { $st = Get-Reg $s.Appr $p.Name $enabled = $true if ($st -is [byte[]] -and $st.Length -gt 0 -and ($st[0] % 2) -eq 1) { $enabled = $false } [void]$items.Add([pscustomobject]@{ Name = $p.Name; Scope = $s.Scope; Appr = $s.Appr; Enabled = $enabled; Cmd = [string]$p.Value }) } } $folder = @(Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | Where-Object { $_.Location -like '*Startup*' }) return @{ Items = @($items); FolderCount = $folder.Count } } # ================================================================ analisis function Invoke-Analysis { Write-Host '' Write-Host ' Analizando tu PC...' -ForegroundColor Cyan $f = New-Object System.Collections.ArrayList function Add-F($Sev, $Title, $Detail, $Fix) { [void]$f.Add([ordered]@{ sev=$Sev; title=$Title; detail=$Detail; fix=$Fix }) } $os = Get-CimInstance Win32_OperatingSystem $cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() $gpuO = Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Microsoft|Virtual|Parsec|Remote' } | Select-Object -First 1 $mods = @(Get-CimInstance Win32_PhysicalMemory) $ramGB = [math]::Round((($mods | Measure-Object Capacity -Sum).Sum / 1GB), 0) $ramMHz = ($mods | Select-Object -First 1).ConfiguredClockSpeed $ramType = switch (($mods | Select-Object -First 1).SMBIOSMemoryType) { 26 {'DDR4'} 34 {'DDR5'} 24 {'DDR3'} 35 {'LPDDR5'} 30 {'LPDDR4'} default {'?'} } $gpu = ''; $refCur = 0; $refMax = 0; $drvDate = $null if ($gpuO) { $gpu = $gpuO.Name; $refCur = [int]$gpuO.CurrentRefreshRate; $refMax = [int]$gpuO.MaxRefreshRate; $drvDate = $gpuO.DriverDate } $isLaptop = @(Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue).Count -gt 0 $ms = Test-ModernStandby # ---------- comunes $su = Get-StartupItems $startupOn = @($su.Items | Where-Object { $_.Enabled }).Count + $su.FolderCount if ($startupOn -gt 8) { $names = (@($su.Items | Where-Object { $_.Enabled } | Select-Object -First 6 -ExpandProperty Name)) -join ', ' Add-F 'medio' "$startupOn programas se abren al iniciar Windows" "Algunos: $names. Ralentizan el arranque y ocupan memoria." 'auto:startup' } $usedPct = [math]::Round(100 - ($os.FreePhysicalMemory / $os.TotalVisibleMemorySize * 100), 0) if ($usedPct -gt 80) { Add-F 'alto' "RAM ocupada al $usedPct %" "Con $ramGB GB vas justo para lo que tienes abierto. Cierra programas o plantea ampliar memoria." 'manual:Administrador de tareas > Procesos > ordenar por Memoria' } $freePct = 100; $freeGB = 0 $c = Get-PSDrive C -ErrorAction SilentlyContinue if ($c) { $freePct = [math]::Round($c.Free / ($c.Free + $c.Used) * 100, 0); $freeGB = [math]::Round($c.Free / 1GB, 0) if ($freePct -lt 15) { Add-F 'alto' "Solo queda un $freePct % libre en C: ($freeGB GB)" 'Con el disco casi lleno Windows va mas lento y las actualizaciones fallan.' 'auto:temp' } } $diskType = '?'; $diskHealth = '?' try { $sysNum = (Get-Partition -DriveLetter C -ErrorAction Stop).DiskNumber $pd = Get-PhysicalDisk | Where-Object { $_.DeviceId -eq [string]$sysNum } | Select-Object -First 1 if ($pd) { $diskType = [string]$pd.MediaType; $diskHealth = [string]$pd.HealthStatus } } catch { } if ($diskType -eq 'HDD') { Add-F 'alto' 'Windows esta en un disco duro mecanico (HDD)' 'Es la causa numero 1 de PCs lentos. Pasar a un SSD multiplica la velocidad de arranque y de todo el sistema.' 'manual:Cambio a SSD con clonado del sistema (te lo hacemos en el servicio 1 a 1)' } if ($diskHealth -and $diskHealth -ne 'Healthy' -and $diskHealth -ne '?') { Add-F 'alto' "El disco del sistema informa estado: $diskHealth" 'Puede estar fallando. Haz copia de seguridad YA.' 'manual:Copia de seguridad inmediata y revision del disco' } $uptimeDays = [math]::Round(((Get-Date) - $os.LastBootUpTime).TotalDays, 1) if ($uptimeDays -gt 7) { Add-F 'bajo' "El PC lleva $uptimeDays dias sin reiniciarse" 'Con el inicio rapido de Windows, "Apagar" no reinicia del todo. Reiniciar de vez en cuando libera memoria y aplica actualizaciones.' 'manual:Inicio > Reiniciar (no Apagar) una vez por semana' } $build = [int]$os.BuildNumber $winEol = $false if ($build -lt 22000) { $winEol = $true; Add-F 'alto' 'Windows 10: sin actualizaciones de seguridad desde octubre de 2025' 'Ya no recibe parches de seguridad gratuitos. Conviene pasar a Windows 11 si el PC es compatible.' 'manual:Actualizacion a Windows 11 o revision de compatibilidad' } try { $mp = Get-MpComputerStatus -ErrorAction Stop if (-not $mp.RealTimeProtectionEnabled) { Add-F 'alto' 'La proteccion en tiempo real del antivirus esta desactivada' 'Si no usas otro antivirus, el PC esta desprotegido.' 'manual:Seguridad de Windows > Proteccion antivirus y contra amenazas' } elseif ($mp.AntivirusSignatureAge -gt 7) { Add-F 'medio' "Las firmas del antivirus tienen $($mp.AntivirusSignatureAge) dias" 'Windows Update no se esta actualizando bien.' 'manual:Configuracion > Windows Update > Buscar actualizaciones' } } catch { } $batWear = $null if ($isLaptop) { try { $full = (Get-CimInstance -Namespace root\wmi -ClassName BatteryFullChargedCapacity -ErrorAction Stop | Select-Object -First 1).FullChargedCapacity $design = (Get-CimInstance -Namespace root\wmi -ClassName BatteryStaticData -ErrorAction Stop | Select-Object -First 1).DesignedCapacity if ($full -gt 0 -and $design -gt 0) { $batWear = [math]::Round(100 - ($full / $design * 100), 0) if ($batWear -gt 30) { Add-F 'medio' "La bateria ha perdido un $batWear % de capacidad" 'Dura bastante menos que cuando era nueva. Se puede sustituir.' 'manual:Cambio de bateria (pide presupuesto)' } } } catch { } } $tempMB = 0 foreach ($tp in @($env:TEMP, "$env:SystemRoot\Temp")) { try { $tempMB += [math]::Round(((Get-ChildItem $tp -Recurse -Force -File -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum / 1MB), 0) } catch { } } # ---------- especificos del perfil if ($script:Perfil -eq 'gamer') { if (($ramType -eq 'DDR4' -and $ramMHz -le 2666) -or ($ramType -eq 'DDR5' -and $ramMHz -le 4800)) { Add-F 'alto' "La RAM funciona a $ramMHz MHz ($ramType)" 'Lo mas probable es que el perfil XMP/EXPO este desactivado. Suele ser la mejora mas grande en los 1% low.' 'manual:BIOS > apartado de memoria > XMP/EXPO: Perfil 1' } if ($refCur -gt 0 -and $refMax -gt $refCur -and $refCur -le 75) { Add-F 'alto' "El monitor va a $refCur Hz y admite hasta $refMax Hz" 'Estas viendo menos fotogramas de los que tu monitor puede mostrar.' 'manual:Configuracion > Sistema > Pantalla > Pantalla avanzada > Frecuencia de actualizacion' } if ($drvDate -and ((Get-Date) - $drvDate).TotalDays -gt 180) { Add-F 'medio' ("El driver de la grafica tiene {0} dias" -f [int]((Get-Date) - $drvDate).TotalDays) 'Los drivers nuevos traen mejoras para juegos recientes.' 'manual:Web de NVIDIA, AMD o Intel' } $pp = Get-PowerPlan if ($ms) { Add-F 'medio' 'Portatil con modo de energia moderno' 'En este tipo de equipos se elige el rendimiento con el control deslizante, no con planes clasicos. Ponlo en "Maximo rendimiento" y juega enchufado.' 'manual:Configuracion > Sistema > Energia y bateria > Modo de energia' } elseif ($pp.Guid -and $pp.Guid -ne $HighPerf -and $pp.Name -notmatch 'Ultimate|M.ximo|Alto|High') { Add-F 'medio' "Plan de energia: $($pp.Name)" 'Windows puede bajar la frecuencia del procesador mientras juegas.' 'auto:power' } if ((Get-Reg $K.GameBar 'AutoGameModeEnabled') -eq 0) { Add-F 'medio' 'El Modo de juego esta desactivado' 'Windows no prioriza el juego frente a otras tareas.' 'auto:gamemode' } if ((Get-Reg $K.Dvr 'HistoricalCaptureEnabled') -eq 1) { Add-F 'medio' 'La Game Bar graba en segundo plano' 'Esta grabando continuamente los ultimos minutos de juego.' 'auto:dvr' } if ((Get-Reg $K.Gfx 'HwSchMode') -ne 2) { Add-F 'bajo' 'Programacion de GPU por hardware desactivada' 'Puede reducir la latencia en graficas modernas. Hay que medir.' 'auto:hags' } if ((Get-Reg 'HKLM:\System\CurrentControlSet\Control' 'PEFirmwareType') -eq 1) { Add-F 'bajo' 'Windows arranca en modo Legacy (BIOS)' 'Sin UEFI no puedes activar Resizable BAR. Cambiarlo requiere convertir el disco a GPT: no lo hagas sin copia.' 'manual:Avanzado: lo hacemos en el servicio 1 a 1' } try { $dg = Get-CimInstance -Namespace root\Microsoft\Windows\DeviceGuard -ClassName Win32_DeviceGuard -ErrorAction Stop if ($dg.VirtualizationBasedSecurityStatus -eq 2) { Add-F 'info' 'Integridad de memoria (VBS) activada' 'Protege Windows y cuesta algo de rendimiento en algunos juegos. Es de nivel EXTREMO: solo si sabes lo que implica.' 'manual:Seguridad de Windows > Seguridad del dispositivo > Aislamiento del nucleo' } } catch { } } else { if ((Get-Reg $K.CDM 'SilentInstalledAppsEnabled') -ne 0 -or (Get-Reg $K.CDM 'SubscribedContent-338388Enabled') -ne 0) { Add-F 'medio' 'Windows muestra anuncios e instala apps patrocinadas' 'Sugerencias en Inicio y apps que aparecen solas (juegos, redes sociales...).' 'auto:ads' } if ((Get-Reg $K.ExplPol 'DisableSearchBoxSuggestions') -ne 1) { Add-F 'bajo' 'El buscador de Inicio busca tambien en Bing' 'Lo que escribes se envia a internet y los resultados tardan mas.' 'auto:bing' } if ((Get-Reg $K.Storage '01') -ne 1) { Add-F 'bajo' 'Sensor de almacenamiento desactivado' 'Windows no limpia solo los temporales ni la papelera.' 'auto:storagesense' } if ($tempMB -gt 1024) { Add-F 'medio' ("{0:N1} GB en archivos temporales" -f ($tempMB / 1024)) 'Espacio ocupado por archivos que ya no se usan.' 'auto:temp' } if ($isLaptop -and $ms) { $pp = Get-PowerPlan Add-F 'info' 'Modo de energia del portatil' 'Con cargador, "Maximo rendimiento" va mas fluido; con bateria, "Equilibrado" dura mas.' 'manual:Configuracion > Sistema > Energia y bateria > Modo de energia' } } $score = 100 foreach ($x in $f) { switch ($x.sev) { 'alto' { $score -= 15 } 'medio' { $score -= 8 } 'bajo' { $score -= 4 } } } if ($score -lt 0) { $score = 0 } $res = [ordered]@{ os = "$($os.Caption) ($build)"; cpu = $cpu; gpu = $gpu ram_gb = $ramGB; ram_mhz = $ramMHz; ram_type = $ramType refresh = $refCur; refresh_max = $refMax startup = $startupOn; procs = (Get-Process).Count; ram_used_pct = $usedPct disk_type = $diskType; disk_free_pct = $freePct; disk_free_gb = $freeGB; temp_mb = $tempMB uptime_days = $uptimeDays; laptop = $isLaptop; battery_wear = $batWear; win_eol = $winEol score = $score; findings = @($f); date = (Get-Date).ToString('s') } Line Write-Host (" {0}" -f $cpu) Write-Host (" {0}" -f $gpu) Write-Host (" {0} GB {1} a {2} MHz | Disco {3}: {4} GB libres | Monitor {5}/{6} Hz" -f $ramGB, $ramType, $ramMHz, $diskType, $freeGB, $refCur, $refMax) Line $col = 'Green'; if ($score -lt 80) { $col = 'Yellow' }; if ($score -lt 55) { $col = 'Red' } $perfTxt = 'USO DIARIO'; if ($script:Perfil -eq 'gamer') { $perfTxt = 'GAMER' } Write-Host (" PUNTUACION ({0}): {1}/100" -f $perfTxt, $score) -ForegroundColor $col Line if ($f.Count -eq 0) { Write-Host ' No he encontrado nada importante. Tu PC esta bien configurado.' -ForegroundColor Green } foreach ($x in $f) { $c2 = switch ($x.sev) { 'alto' {'Red'} 'medio' {'Yellow'} 'bajo' {'Gray'} default {'Cyan'} } Write-Host (" [{0}] {1}" -f $x.sev.ToUpper(), $x.title) -ForegroundColor $c2 Write-Host (" {0}" -f $x.detail) -ForegroundColor DarkGray if ($x.fix -like 'auto:*') { Write-Host ' -> Lo arreglo yo desde el menu' -ForegroundColor Green } else { Write-Host (" -> Hazlo tu: {0}" -f $x.fix.Substring(7)) -ForegroundColor Cyan } } $st = Read-Json $StateFile $st['analysis'] = $res if (-not $st['applied'] -or @($st['applied']).Count -eq 0) { $st['analysis_before'] = $res } else { $st['analysis_after'] = $res } Save-Json $st $StateFile Write-Host '' Write-Host ' Si prefieres que te lo dejemos perfecto nosotros: optimizacion.civicloud.es/#servicios' -ForegroundColor DarkGray } # ================================================================ FPS (gamer) function Get-PresentMon { $exe = Join-Path $Dir 'PresentMon.exe' if (Test-Path $exe) { return $exe } Write-Host ' Descargando PresentMon (herramienta oficial de Intel, codigo abierto)...' -ForegroundColor Cyan try { $rel = Invoke-RestMethod 'https://api.github.com/repos/GameTechDev/PresentMon/releases/latest' -Headers @{ 'User-Agent' = 'Optimiza' } $asset = $rel.assets | Where-Object { $_.name -match '^PresentMon-[\d\.]+-x64\.exe$' } | Select-Object -First 1 if (-not $asset) { throw 'No encuentro el ejecutable en la ultima version.' } Invoke-WebRequest $asset.browser_download_url -OutFile $exe -UseBasicParsing return $exe } catch { Write-Host " No se pudo descargar PresentMon: $($_.Exception.Message)" -ForegroundColor Red; return $null } } function Measure-Fps { $pm = Get-PresentMon if (-not $pm) { return } $noGames = '^(explorer|WindowsTerminal|powershell|pwsh|conhost|ApplicationFrameHost|TextInputHost|SystemSettings|msedge|chrome|firefox|opera|brave|OUTLOOK|WINWORD|EXCEL|POWERPNT|ms-teams|Teams|claude|rustdesk|AnyDesk|TeamViewer|Discord|Spotify|Code|notepad|Acrobat|AcroRd32|steamwebhelper|EpicGamesLauncher|Battle\.net|obs64|ShellExperienceHost|StartMenuExperienceHost|SearchHost|LockApp)$' $procs = @(Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.ProcessName -notmatch $noGames } | Sort-Object CPU -Descending | Select-Object -First 10) Write-Host '' if ($procs.Count -eq 0) { Write-Host ' No veo ningun juego abierto.' -ForegroundColor Yellow Write-Host ' Abre el juego, ponte en una situacion repetible (repeticion, benchmark, modo entrenamiento) y vuelve a elegir esta opcion.' return } Write-Host ' Juegos y programas abiertos:' for ($i = 0; $i -lt $procs.Count; $i++) { Write-Host (" {0}) {1} [{2}]" -f ($i + 1), $procs[$i].ProcessName, $procs[$i].MainWindowTitle) } $sel = Read-Host ' Numero del juego (Enter para volver)' if ([string]::IsNullOrWhiteSpace($sel)) { return } $n = 0 if (-not [int]::TryParse($sel, [ref]$n) -or $n -lt 1 -or $n -gt $procs.Count) { Write-Host ' Opcion no valida.'; return } $p = $procs[$n - 1] $csv = Join-Path $Dir ("fps_{0}.csv" -f (Get-Date -Format 'yyyyMMdd_HHmmss')) Write-Host '' Write-Host ' Vuelve al juego. Empiezo a medir en 10 segundos y mido 60 segundos...' -ForegroundColor Cyan Start-Sleep -Seconds 10 & $pm --process_name ("{0}.exe" -f $p.ProcessName) --output_file $csv --timed 60 --terminate_after_timed 2>&1 | Out-Null if (-not (Test-Path $csv)) { Write-Host ' No se han registrado fotogramas. Juega en pantalla completa y repite.' -ForegroundColor Red; return } $rows = @(Import-Csv $csv) if ($rows.Count -eq 0) { Write-Host ' El archivo de medicion esta vacio.' -ForegroundColor Red; return } $col = @('MsBetweenPresents', 'FrameTime', 'MsBetweenAppStart') | Where-Object { $rows[0].PSObject.Properties.Name -contains $_ } | Select-Object -First 1 if (-not $col) { Write-Host ' Formato de PresentMon no reconocido.' -ForegroundColor Red; return } $ft = @($rows | ForEach-Object { $v = 0.0; if ([double]::TryParse($_.$col, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$v)) { $v } } | Where-Object { $_ -gt 0 -and $_ -lt 1000 }) if ($ft.Count -lt 100) { Write-Host ' Muy pocos fotogramas medidos. Repite con el juego en primer plano.' -ForegroundColor Red; return } $avg = 1000 / ($ft | Measure-Object -Average).Average $worst = $ft | Sort-Object -Descending | Select-Object -First ([math]::Max(1, [int]($ft.Count / 100))) $low = 1000 / ($worst | Measure-Object -Average).Average $m = [ordered]@{ game = $p.ProcessName; avg = [math]::Round($avg, 1); low1 = [math]::Round($low, 1); frames = $ft.Count; date = (Get-Date).ToString('s') } $st = Read-Json $StateFile $slot = 'fps_before'; if ($st['applied'] -and @($st['applied']).Count -gt 0) { $slot = 'fps_after' } $st[$slot] = $m; Save-Json $st $StateFile Line Write-Host (" {0}: {1} FPS de media | 1% low: {2} FPS" -f $m.game, $m.avg, $m.low1) -ForegroundColor Green if ($slot -eq 'fps_before') { Write-Host ' Guardado como ANTES. Optimiza y vuelve a medir en la misma situacion.' } elseif ($st['fps_before']) { $b = $st['fps_before'] $d1 = [math]::Round(($m.avg - $b.avg) / $b.avg * 100, 1); $d2 = [math]::Round(($m.low1 - $b.low1) / $b.low1 * 100, 1) Write-Host (" Antes: {0} / {1} -> Diferencia: {2}% media, {3}% en 1% low" -f $b.avg, $b.low1, $d1, $d2) -ForegroundColor Cyan } } # ================================================================ limpieza (uso diario) function Invoke-Cleanup { Write-Host '' Write-Host ' Borra archivos temporales de mas de 2 dias (tuyos y de Windows) y vacia la papelera.' -ForegroundColor Cyan Write-Host ' Son archivos que ya no se usan. Esto NO se puede deshacer, pero no toca tus documentos.' -ForegroundColor DarkGray if (-not (Ask ' Continuar?')) { return } $freed = 0 $limit = (Get-Date).AddDays(-2) foreach ($tp in @($env:TEMP, "$env:SystemRoot\Temp")) { Get-ChildItem $tp -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $limit } | ForEach-Object { $len = $_.Length try { Remove-Item $_.FullName -Force -ErrorAction Stop; $freed += $len } catch { } } } try { Clear-RecycleBin -Force -ErrorAction SilentlyContinue } catch { } $mb = [math]::Round($freed / 1MB, 0) $st = Read-Json $StateFile $prev = 0; if ($st['temp_freed_mb']) { $prev = [int]$st['temp_freed_mb'] } $st['temp_freed_mb'] = $prev + $mb; Save-Json $st $StateFile Write-Host (" Liberados {0} MB (mas la papelera)." -f $mb) -ForegroundColor Green } # ================================================================ programas de inicio function Invoke-Startup { $su = Get-StartupItems $list = @($su.Items) if ($list.Count -eq 0) { Write-Host ' No hay programas de inicio en el registro.' -ForegroundColor Yellow; return } Write-Host '' Write-Host ' Programas que se abren al iniciar Windows:' -ForegroundColor Cyan for ($i = 0; $i -lt $list.Count; $i++) { $state = 'ACTIVO'; $c = 'White' if (-not $list[$i].Enabled) { $state = 'desactivado'; $c = 'DarkGray' } Write-Host (" {0,2}) {1,-38} {2,-12} {3}" -f ($i + 1), $list[$i].Name, $list[$i].Scope, $state) -ForegroundColor $c } if ($su.FolderCount -gt 0) { Write-Host (" + {0} en la carpeta Inicio (gestionalos en Configuracion > Aplicaciones > Inicio)" -f $su.FolderCount) -ForegroundColor DarkGray } Write-Host '' Write-Host ' Consejo: deja el antivirus, los drivers (audio, touchpad, graficos) y lo que uses nada mas encender.' -ForegroundColor DarkGray $sel = Read-Host ' Numeros a DESACTIVAR separados por comas (Enter para volver)' if ([string]::IsNullOrWhiteSpace($sel)) { return } $bk = Read-Json $BackupFile $st = Read-Json $StateFile $count = 0 foreach ($tok in ($sel -split '[,\s]+')) { $n = 0 if (-not [int]::TryParse($tok, [ref]$n) -or $n -lt 1 -or $n -gt $list.Count) { continue } $it = $list[$n - 1] if (-not $it.Enabled) { continue } try { Backup-Value $bk $it.Appr $it.Name 'Binary' $bytes = New-Object byte[] 12; $bytes[0] = 3 Set-Reg $it.Appr $it.Name $bytes 'Binary' Write-Host (" [OK] Desactivado: {0}" -f $it.Name) -ForegroundColor Green $count++ } catch { Write-Host (" [X] {0}: {1}" -f $it.Name, $_.Exception.Message) -ForegroundColor Red } } Save-Json $bk $BackupFile $prev = 0; if ($st['startup_disabled']) { $prev = [int]$st['startup_disabled'] } $st['startup_disabled'] = $prev + $count $ap = New-Object System.Collections.ArrayList if ($st['applied']) { foreach ($a in @($st['applied'])) { [void]$ap.Add($a) } } if ($count -gt 0 -and $ap -notcontains 'startup') { [void]$ap.Add('startup') } $st['applied'] = @($ap); Save-Json $st $StateFile Write-Host ' Se aplica en el proximo inicio. Puedes volver a activarlos con "Deshacer" o desde Configuracion > Aplicaciones > Inicio.' -ForegroundColor DarkGray } # ================================================================ aplicar / revertir function Invoke-Optimize([string]$Level) { $ms = Test-ModernStandby $sel = @($Tweaks | Where-Object { $_.Perfil -eq $script:Perfil -and ($_.Nivel -eq 'leve' -or ($Level -eq 'moderado' -and $_.Nivel -eq 'moderado')) }) if ($ms) { $sel = @($sel | Where-Object { $_.Id -ne 'power' }) } Write-Host '' Write-Host (" Voy a aplicar {0} ajustes (nivel {1}):" -f $sel.Count, $Level.ToUpper()) -ForegroundColor Cyan foreach ($t in $sel) { Write-Host (" - {0}: {1}" -f $t.Nombre, $t.Desc) } if ($ms -and $script:Perfil -eq 'gamer') { Write-Host ' * Energia: en tu portatil ponlo tu en Configuracion > Sistema > Energia y bateria > Maximo rendimiento.' -ForegroundColor Yellow } Write-Host ' Todo queda guardado para poder deshacerlo.' -ForegroundColor DarkGray if (-not (Ask ' Continuar?')) { return } try { Enable-ComputerRestore -Drive "$env:SystemDrive\" -ErrorAction SilentlyContinue $wv = $null Checkpoint-Computer -Description "Optimiza $Version" -RestorePointType MODIFY_SETTINGS -ErrorAction Stop -WarningAction SilentlyContinue -WarningVariable wv if ($wv) { Write-Host ' Ya hay un punto de restauracion de las ultimas 24 h (Windows solo permite uno al dia). Sigo: los cambios se pueden deshacer igual.' -ForegroundColor Yellow } else { Write-Host ' Punto de restauracion creado.' -ForegroundColor Green } } catch { Write-Host ' No se ha podido crear el punto de restauracion. Sigo: los cambios se pueden deshacer igual.' -ForegroundColor Yellow } $bk = Read-Json $BackupFile $st = Read-Json $StateFile $applied = New-Object System.Collections.ArrayList if ($st['applied']) { foreach ($a in @($st['applied'])) { [void]$applied.Add($a) } } $reboot = $false; $explorer = $false foreach ($t in $sel) { try { if ($t.Id -eq 'power') { $pp = Get-PowerPlan if (-not $bk.ContainsKey('powerplan')) { $bk['powerplan'] = $pp.Guid } $list = (powercfg /list) | Out-String if ($list -notmatch $HighPerf) { powercfg -duplicatescheme $HighPerf $HighPerf 2>$null | Out-Null } powercfg /setactive $HighPerf 2>$null } else { foreach ($r in $t.Reg) { Backup-Value $bk $r.P $r.N $r.T; Set-Reg $r.P $r.N $r.V $r.T } if ($t.Id -eq 'hags') { $reboot = $true } if ($t.Id -in @('bing', 'animations', 'ads')) { $explorer = $true } } if ($applied -notcontains $t.Id) { [void]$applied.Add($t.Id) } Write-Host (" [OK] {0}" -f $t.Nombre) -ForegroundColor Green } catch { Write-Host (" [X] {0}: {1}" -f $t.Nombre, $_.Exception.Message) -ForegroundColor Red } } Save-Json $bk $BackupFile $st['applied'] = @($applied); $st['level'] = $Level; Save-Json $st $StateFile Line Write-Host ' Hecho.' -ForegroundColor Green if ($reboot) { Write-Host ' Reinicia el PC para que se apliquen todos los cambios.' -ForegroundColor Yellow } elseif ($explorer) { Write-Host ' Cierra sesion o reinicia para ver todos los cambios.' -ForegroundColor Yellow } if ($script:Perfil -eq 'gamer') { Write-Host ' Despues mide otra vez los FPS (opcion 2) en la misma situacion para comparar.' } else { Write-Host ' Despues vuelve a analizar (opcion 1) para ver la puntuacion nueva.' } } function Invoke-Revert { $bk = Read-Json $BackupFile if ($bk.Count -eq 0) { Write-Host ' No hay cambios que deshacer.' -ForegroundColor Yellow; return } if (-not (Ask ' Deshacer TODOS los cambios de Optimiza?')) { return } foreach ($k in @($bk.Keys)) { try { if ($k -eq 'powerplan') { if ($bk[$k]) { powercfg /setactive $bk[$k] 2>$null } } else { $e = $bk[$k] if ($null -eq $e.old) { Remove-ItemProperty -Path $e.path -Name $e.name -ErrorAction SilentlyContinue } else { Set-Reg $e.path $e.name $e.old $e.type } } } catch { Write-Host " No se pudo restaurar $k" -ForegroundColor Red } } Remove-Item $BackupFile -Force $st = Read-Json $StateFile $st['applied'] = @(); $st.Remove('fps_after'); $st.Remove('analysis_after'); $st.Remove('startup_disabled'); $st.Remove('level') Save-Json $st $StateFile Write-Host ' Todo restaurado (los archivos temporales borrados no vuelven, no hacen falta). Reinicia el PC.' -ForegroundColor Green } # ================================================================ informe function Send-Report { $st = Read-Json $StateFile if (-not $st['analysis_before']) { Write-Host ' Primero haz el analisis (opcion 1).' -ForegroundColor Yellow; return } Write-Host '' Write-Host ' Se enviara de forma ANONIMA: modelo de CPU/GPU/RAM/disco, version de Windows, resultados' Write-Host ' del analisis, ajustes aplicados y mediciones. Nada de nombres, usuarios, programas ni archivos.' if (-not (Ask ' Subir el informe y abrirlo en la web?')) { return } $payload = [ordered]@{ version = $Version; perfil = $script:Perfil; level = $st['level']; applied = @($st['applied']) analysis_before = $st['analysis_before']; analysis_after = $st['analysis_after'] fps_before = $st['fps_before']; fps_after = $st['fps_after'] temp_freed_mb = $st['temp_freed_mb']; startup_disabled = $st['startup_disabled'] } try { $json = $payload | ConvertTo-Json -Depth 8 -Compress $r = Invoke-RestMethod -Uri "$Base/api/report.php" -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($json)) if ($r.ok) { $url = "$Base/informe.html?id=$($r.id)" Write-Host " Informe: $url" -ForegroundColor Green Start-Process $url } else { Write-Host " Error: $($r.message)" -ForegroundColor Red } } catch { Write-Host " No se pudo subir: $($_.Exception.Message)" -ForegroundColor Red } } # ================================================================ perfil + menu function Select-Perfil { Write-Host '' Write-Host ' Para que usas principalmente este PC?' -ForegroundColor Cyan Write-Host ' 1) Uso diario: trabajo, estudios, navegar, ofimatica' Write-Host ' 2) Gaming' $r = Read-Host ' Elige' $p = 'usuario'; if ($r -eq '2') { $p = 'gamer' } $st = Read-Json $StateFile if ($st['perfil'] -and $st['perfil'] -ne $p) { $st.Remove('analysis_before'); $st.Remove('analysis_after'); $st.Remove('analysis') } $st['perfil'] = $p; Save-Json $st $StateFile return $p } $script:Perfil = (Read-Json $StateFile)['perfil'] if (-not $script:Perfil) { $script:Perfil = Select-Perfil } while ($true) { $isGamer = ($script:Perfil -eq 'gamer') $pt = 'USO DIARIO'; if ($isGamer) { $pt = 'GAMER' } Write-Host '' Write-Host ' ===============================================' -ForegroundColor Red Write-Host (" OPTIMIZA v{0} - perfil {1}" -f $Version, $pt) -ForegroundColor Red Write-Host ' ===============================================' -ForegroundColor Red Write-Host ' 1) Analizar mi PC (no cambia nada)' if ($isGamer) { Write-Host ' 2) Medir FPS de un juego (60 s)' } else { Write-Host ' 2) Liberar espacio (temporales y papelera)' } Write-Host ' 3) Optimizar - nivel LEVE (seguro)' Write-Host ' 4) Optimizar - nivel MODERADO' Write-Host ' 5) Elegir programas de inicio' Write-Host ' 6) Deshacer todos los cambios' Write-Host ' 7) Subir informe y verlo en la web' Write-Host ' 8) Cambiar de perfil' Write-Host ' 0) Salir' $op = Read-Host ' Elige' switch ($op) { '1' { Invoke-Analysis } '2' { if ($isGamer) { Measure-Fps } else { Invoke-Cleanup } } '3' { Invoke-Optimize 'leve' } '4' { Invoke-Optimize 'moderado' } '5' { Invoke-Startup } '6' { Invoke-Revert } '7' { Send-Report } '8' { $script:Perfil = Select-Perfil } '0' { return } default { Write-Host ' Opcion no valida.' } } } } Start-Optimiza