OptimizarPC

Gerador de scripts PowerShell para Windows 11

Optimizações

Selecciona o que queres incluir no script

19 activas

🧹Limpeza

4/5

Arranque

2/2

🧠RAM & CPU

4/4

💾Disco

2/2

🌐Rede

3/3

🔧Windows Tweaks

4/4

Mantém esta página aberta — o progresso de cada optimização aparece ao lado em tempo real.

OptimizarPC.ps1
19 optimizações~5.3 GB26.4 GB estimados
#Requires -RunAsAdministrator
<#
  ____        _   _           _              ____   ____
 / __ \      | | (_)         (_)            |  _ \ / ___|
| |  | |_ __ | |_ _ _ __ ___  _ ______ _ _ _| |_) | |
| |  | | '_ \| __| | '_ ` _ \| |_  / _` | '__|  __/| |
| |__| | |_) | |_| | | | | | | |/ / (_| | |  | |   | |___
 \____/| .__/ \__|_|_| |_| |_|_/___\__,_|_|  |_|    \____|
       | |
       |_|   Gerador de optimizacoes para Windows 11
#>

$ErrorActionPreference = 'SilentlyContinue'
$ProgressPreference = 'SilentlyContinue'

# Helper para emptyworkingset
Add-Type -Name psapi -Namespace '' -MemberDefinition @"
[System.Runtime.InteropServices.DllImport("psapi.dll")]
public static extern int EmptyWorkingSet(System.IntPtr hProcess);
"@ -ErrorAction SilentlyContinue

# --- Progresso em tempo real para a página web ---
$script:ProgressUrl = ''
$script:ProgressEnabled = $false
function Send-Progress($stepId, $status, $message) {
    if (-not $script:ProgressEnabled) { return }
    try {
        $payload = @{ step_id = $stepId; status = $status; message = $message } | ConvertTo-Json -Compress
        Invoke-RestMethod -Uri $script:ProgressUrl -Method POST -ContentType 'application/json' -Body $payload -TimeoutSec 4 | Out-Null
    } catch { }
}

function Write-Section($title) {
    Write-Host ""
    Write-Host ("=" * 70) -ForegroundColor Cyan
    Write-Host "  $title" -ForegroundColor Cyan
    Write-Host ("=" * 70) -ForegroundColor Cyan
}

function Get-SystemState {
    $disk = Get-PSDrive -Name C
    $os = Get-CimInstance Win32_OperatingSystem
    $ramFreeGB = [math]::Round($os.FreePhysicalMemory / 1MB, 2)
    $ramTotalGB = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
    $uptime = (Get-Date) - $os.LastBootUpTime
    return [PSCustomObject]@{
        DiscoLivreGB = [math]::Round($disk.Free / 1GB, 2)
        DiscoTotalGB = [math]::Round(($disk.Free + $disk.Used) / 1GB, 2)
        RAMLivreGB = $ramFreeGB
        RAMTotalGB = $ramTotalGB
        UptimeHoras = [math]::Round($uptime.TotalHours, 1)
    }
}

function Get-FolderSizeMB($path) {
    if (-not (Test-Path $path)) { return 0 }
    try {
        $bytes = (Get-ChildItem -Path $path -Recurse -Force -ErrorAction SilentlyContinue |
                  Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum
        if ($null -eq $bytes) { return 0 }
        return [math]::Round($bytes / 1MB, 0)
    } catch { return 0 }
}

function Format-MB($mb) {
    if ($mb -ge 1024) { return ("{0:N2} GB" -f ($mb / 1024)) }
    return ("{0} MB" -f $mb)
}

Clear-Host
Write-Host ""
Write-Host "  OptimizarPC — Windows 11" -ForegroundColor Cyan
Write-Host "  -------------------------" -ForegroundColor DarkCyan
Write-Host ""

$inicio = Get-SystemState
Write-Host "  Estado inicial:" -ForegroundColor White
Write-Host ("    Disco C: livre   {0} GB / {1} GB" -f $inicio.DiscoLivreGB, $inicio.DiscoTotalGB) -ForegroundColor Gray
Write-Host ("    RAM livre        {0} GB / {1} GB" -f $inicio.RAMLivreGB, $inicio.RAMTotalGB) -ForegroundColor Gray
Write-Host ("    Uptime           {0} horas" -f $inicio.UptimeHoras) -ForegroundColor Gray
Write-Host ""

# ============= ANÁLISE DO SISTEMA =============
Write-Section "🔍 Análise do sistema"
Write-Host ""
$espacoEstimado = 0

$s = Get-FolderSizeMB "$env:TEMP"; $s2 = Get-FolderSizeMB "C:\Windows\Temp"; $s3 = Get-FolderSizeMB "C:\Windows\Prefetch"; $s4 = Get-FolderSizeMB "$env:LOCALAPPDATA\Microsoft\Windows\INetCache"
$tot = $s + $s2 + $s3 + $s4; $espacoEstimado += $tot
Write-Host ("  • Ficheiros temporários:    {0,10}" -f (Format-MB $tot)) -ForegroundColor White

$s = Get-FolderSizeMB "C:\Windows\SoftwareDistribution\Download"; $espacoEstimado += $s
Write-Host ("  • Cache Windows Update:     {0,10}" -f (Format-MB $s)) -ForegroundColor White

$logCount = (wevtutil el | Measure-Object).Count
Write-Host ("  • Logs de eventos:          {0,10} canais" -f $logCount) -ForegroundColor White

$s = Get-FolderSizeMB "$env:LOCALAPPDATA\Microsoft\Windows\Explorer"; $espacoEstimado += $s
Write-Host ("  • Cache de miniaturas:      {0,10}" -f (Format-MB $s)) -ForegroundColor White

$svcInfo = @()
foreach ($n in @('SysMain','DiagTrack','WSearch')) {
    $svc = Get-Service -Name $n -ErrorAction SilentlyContinue
    if ($svc -and $svc.Status -eq 'Running') {
        $proc = Get-Process -Name $n -ErrorAction SilentlyContinue | Select-Object -First 1
        $ram = if ($proc) { [math]::Round($proc.WorkingSet64 / 1MB, 0) } else { 0 }
        $svcInfo += "$n ($ram MB)"
    }
}
$svcStr = if ($svcInfo.Count -gt 0) { $svcInfo -join ', ' } else { 'nenhum activo' }
Write-Host ("  • Serviços pesados activos: {0}" -f $svcStr) -ForegroundColor White

$apps = @()
Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | ForEach-Object {
    foreach ($n in @('Teams','OneDrive','Spotify','Discord')) {
        if ($_.Name -like "*$n*") { $apps += $_.Name }
    }
}
$appsStr = if ($apps.Count -gt 0) { $apps -join ', ' } else { 'nenhuma encontrada' }
Write-Host ("  • Apps no arranque:         {0}" -f $appsStr) -ForegroundColor White

$bg = Get-Process | Where-Object { $_.WorkingSet -gt 50MB -and $_.MainWindowHandle -eq 0 }
$bgRam = [math]::Round(($bg | Measure-Object -Property WorkingSet -Sum).Sum / 1MB, 0)
Write-Host ("  • RAM em background:        {0,10}  ({1} processos)" -f (Format-MB $bgRam), $bg.Count) -ForegroundColor White

$hib = "C:\hiberfil.sys"
if (Test-Path $hib) {
    $s = [math]::Round((Get-Item $hib -Force).Length / 1MB, 0); $espacoEstimado += $s
    Write-Host ("  • hiberfil.sys:             {0,10}" -f (Format-MB $s)) -ForegroundColor White
} else {
    Write-Host  "  • hiberfil.sys:             (já desactivado)" -ForegroundColor DarkGray
}

$cur = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\PriorityControl" -Name "Win32PrioritySeparation" -ErrorAction SilentlyContinue).Win32PrioritySeparation
Write-Host ("  • CPU scheduling actual:    {0,10}  (vai mudar para 38 = foreground)" -f $cur) -ForegroundColor White

$gdvr = (Get-ItemProperty -Path "HKCU:\System\GameConfigStore" -Name "GameDVR_Enabled" -ErrorAction SilentlyContinue).GameDVR_Enabled
$st = if ($gdvr -eq 0) { 'já desactivado' } else { 'activo (vai ser desactivado)' }
Write-Host ("  • Game DVR / Game Bar:      {0}" -f $st) -ForegroundColor White

Write-Host  "  • Limpeza avançada cleanmgr: vai correr (todas as categorias)" -ForegroundColor White

$discos = Get-PhysicalDisk | Where-Object { $_.BusType -ne 'USB' } | ForEach-Object { "$($_.MediaType) ($($_.FriendlyName))" }
$discoStr = if ($discos) { $discos -join ', ' } else { 'n/a' }
Write-Host ("  • Discos detectados:        {0}" -f $discoStr) -ForegroundColor White

$cache = (Get-DnsClientCache -ErrorAction SilentlyContinue | Measure-Object).Count
Write-Host ("  • Cache DNS actual:         {0,10} entradas" -f $cache) -ForegroundColor White

$dns = Get-DnsClientServerAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.ServerAddresses } | Select-Object -First 1
$dnsStr = if ($dns) { $dns.ServerAddresses -join ', ' } else { 'auto' }
Write-Host ("  • DNS actual:               {0}  (vai mudar para 1.1.1.1 / 1.0.0.1)" -f $dnsStr) -ForegroundColor White

Write-Host  "  • Nagle TCP:                vai ser desactivado em todos os adaptadores" -ForegroundColor White

$plan = (powercfg -getactivescheme) -replace '.*\((.*)\).*','$1'
Write-Host ("  • Plano energia actual:     {0}  (vai mudar para Ultimate Performance)" -f $plan) -ForegroundColor White

$tel = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection" -Name "AllowTelemetry" -ErrorAction SilentlyContinue).AllowTelemetry
$st = if ($tel -eq 0) { 'já no mínimo' } else { "actual: $tel (vai ser reduzida para 0)" }
Write-Host ("  • Telemetria:               {0}" -f $st) -ForegroundColor White

$fx = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects" -Name "VisualFXSetting" -ErrorAction SilentlyContinue).VisualFXSetting
$st = switch ($fx) { 0 {'Auto'} 1 {'Aparência'} 2 {'Desempenho'} 3 {'Personalizado'} default {'Auto'} }
Write-Host ("  • Efeitos visuais:          {0}  (vai mudar para Desempenho)" -f $st) -ForegroundColor White

$tn = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "ToastEnabled" -ErrorAction SilentlyContinue).ToastEnabled
$st = if ($tn -eq 0) { 'já desactivadas' } else { 'activas (vão ser desactivadas)' }
Write-Host ("  • Notificações:             {0}" -f $st) -ForegroundColor White

Write-Host ""
Write-Host ("  ➜ Espaço estimado a libertar: ~{0}" -f (Format-MB $espacoEstimado)) -ForegroundColor Green
Write-Host ""
$confirm = Read-Host "  Continuar com as optimizações? (s/n)"
if ($confirm -notmatch '^[sSyY]') {
    Write-Host ""
    Write-Host "  Cancelado pelo utilizador. Nenhuma alteração feita." -ForegroundColor Yellow
    Write-Host ""
    Read-Host "Pressiona Enter para sair"
    exit 0
}
Start-Sleep -Seconds 1
Send-Progress '_start' 'running' $null

Write-Section "🧹 Limpeza"

# --- Ficheiros temporários (%TEMP%, Prefetch, INetCache) ---
Send-Progress 'temp' 'running' $null
try {
Write-Host "→ A limpar ficheiros temporários..." -ForegroundColor Yellow
Get-ChildItem -Path "$env:TEMP" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path "C:\Windows\Temp" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path "C:\Windows\Prefetch" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path "$env:LOCALAPPDATA\Microsoft\Windows\INetCache" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "✓ Ficheiros temporários limpos" -ForegroundColor Green
    Send-Progress 'temp' 'done' $null
} catch {
    Send-Progress 'temp' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Ficheiros temporários (%TEMP%, Prefetch, INetCache): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Cache do Windows Update ---
Send-Progress 'wuCache' 'running' $null
try {
Write-Host "→ A limpar cache do Windows Update..." -ForegroundColor Yellow
Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue
Stop-Service -Name bits -Force -ErrorAction SilentlyContinue
Remove-Item "C:\Windows\SoftwareDistribution\Download\*" -Recurse -Force -ErrorAction SilentlyContinue
Start-Service -Name wuauserv -ErrorAction SilentlyContinue
Start-Service -Name bits -ErrorAction SilentlyContinue
Write-Host "✓ Cache do Windows Update limpa" -ForegroundColor Green
    Send-Progress 'wuCache' 'done' $null
} catch {
    Send-Progress 'wuCache' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Cache do Windows Update: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Logs de eventos antigos ---
Send-Progress 'eventLogs' 'running' $null
try {
Write-Host "→ A limpar logs de eventos antigos..." -ForegroundColor Yellow
wevtutil el | ForEach-Object { wevtutil cl "$_" 2>$null }
Write-Host "✓ Logs limpos" -ForegroundColor Green
    Send-Progress 'eventLogs' 'done' $null
} catch {
    Send-Progress 'eventLogs' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Logs de eventos antigos: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Cache de miniaturas (thumbnails) ---
Send-Progress 'thumbs' 'running' $null
try {
Write-Host "→ A limpar cache de miniaturas..." -ForegroundColor Yellow
Stop-Process -Name explorer -Force -ErrorAction SilentlyContinue
Remove-Item "$env:LOCALAPPDATA\Microsoft\Windows\Explorer\thumbcache_*.db" -Force -ErrorAction SilentlyContinue
Start-Process explorer
Write-Host "✓ Cache de miniaturas limpa" -ForegroundColor Green
    Send-Progress 'thumbs' 'done' $null
} catch {
    Send-Progress 'thumbs' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Cache de miniaturas (thumbnails): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "⚡ Arranque"

# --- Desactivar serviços pesados no boot (SysMain, DiagTrack, WSearch) ---
Send-Progress 'heavyServices' 'running' $null
try {
Write-Host "→ A desactivar serviços pesados..." -ForegroundColor Yellow
$svcs = @('SysMain','DiagTrack','WSearch')
foreach ($s in $svcs) {
    Stop-Service -Name $s -Force -ErrorAction SilentlyContinue
    Set-Service -Name $s -StartupType Disabled -ErrorAction SilentlyContinue
    Write-Host "   • $s desactivado" -ForegroundColor DarkGray
}
Write-Host "✓ Serviços pesados desactivados" -ForegroundColor Green
    Send-Progress 'heavyServices' 'done' $null
} catch {
    Send-Progress 'heavyServices' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Desactivar serviços pesados no boot (SysMain, DiagTrack, WSearch): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Remover apps do arranque automático (Teams, OneDrive, Spotify, Discord) ---
Send-Progress 'startupApps' 'running' $null
try {
Write-Host "→ A remover apps do arranque..." -ForegroundColor Yellow
$names = @('Teams','OneDrive','Spotify','Discord','MicrosoftTeams')
foreach ($n in $names) {
    Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "*$n*" } | ForEach-Object {
        Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name $_.Name -ErrorAction SilentlyContinue
        Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name $_.Name -ErrorAction SilentlyContinue
        Write-Host "   • $($_.Name) removido" -ForegroundColor DarkGray
    }
}
Write-Host "✓ Apps de arranque limpas" -ForegroundColor Green
    Send-Progress 'startupApps' 'done' $null
} catch {
    Send-Progress 'startupApps' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Remover apps do arranque automático (Teams, OneDrive, Spotify, Discord): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "🧠 RAM & CPU"

# --- Libertar working set dos processos em background ---
Send-Progress 'workingSet' 'running' $null
try {
Write-Host "→ A libertar memória de processos em background..." -ForegroundColor Yellow
Get-Process | Where-Object { $_.WorkingSet -gt 50MB -and $_.MainWindowHandle -eq 0 } | ForEach-Object {
    try { [void][psapi]::EmptyWorkingSet($_.Handle) } catch {}
}
# Fallback usando rundll32
rundll32.exe advapi32.dll,ProcessIdleTasks
Write-Host "✓ Working set libertado" -ForegroundColor Green
    Send-Progress 'workingSet' 'done' $null
} catch {
    Send-Progress 'workingSet' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Libertar working set dos processos em background: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Desactivar hibernação (liberta espaço = tamanho da RAM) ---
Send-Progress 'hibernate' 'running' $null
try {
Write-Host "→ A desactivar hibernação..." -ForegroundColor Yellow
powercfg /hibernate off
Write-Host "✓ Hibernação desactivada (hiberfil.sys removido)" -ForegroundColor Green
    Send-Progress 'hibernate' 'done' $null
} catch {
    Send-Progress 'hibernate' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Desactivar hibernação (liberta espaço = tamanho da RAM): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Optimizar scheduling do CPU (prioridade para apps em 1º plano) ---
Send-Progress 'cpuSched' 'running' $null
try {
Write-Host "→ A optimizar scheduling do CPU..." -ForegroundColor Yellow
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\PriorityControl" -Name "Win32PrioritySeparation" -Value 38 -Force
Write-Host "✓ CPU priorizado para foreground" -ForegroundColor Green
    Send-Progress 'cpuSched' 'done' $null
} catch {
    Send-Progress 'cpuSched' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Optimizar scheduling do CPU (prioridade para apps em 1º plano): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Desactivar Game DVR / Xbox Game Bar ---
Send-Progress 'gameDvr' 'running' $null
try {
Write-Host "→ A desactivar Game DVR / Game Bar..." -ForegroundColor Yellow
Set-ItemProperty -Path "HKCU:\System\GameConfigStore" -Name "GameDVR_Enabled" -Value 0 -Force -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR" -Name "AllowGameDVR" -Value 0 -Force -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKCU:\Software\Microsoft\GameBar" -Name "UseNexusForGameBarEnabled" -Value 0 -Force -ErrorAction SilentlyContinue
Write-Host "✓ Game DVR desactivado" -ForegroundColor Green
    Send-Progress 'gameDvr' 'done' $null
} catch {
    Send-Progress 'gameDvr' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Desactivar Game DVR / Xbox Game Bar: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "💾 Disco"

# --- Limpeza avançada (cleanmgr silencioso, todas as categorias) ---
Send-Progress 'cleanmgr' 'running' $null
try {
Write-Host "→ A executar limpeza avançada (cleanmgr)..." -ForegroundColor Yellow
$keys = 'Active Setup Temp Folders','BranchCache','Downloaded Program Files','Internet Cache Files','Memory Dump Files','Old ChkDsk Files','Previous Installations','Recycle Bin','Service Pack Cleanup','Setup Log Files','System error memory dump files','System error minidump files','Temporary Files','Temporary Setup Files','Thumbnail Cache','Update Cleanup','Upgrade Discarded Files','Windows Defender','Windows Error Reporting Files','Windows Upgrade Log Files'
foreach ($k in $keys) {
    $path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\$k"
    if (Test-Path $path) {
        New-ItemProperty -Path $path -Name "StateFlags0099" -Value 2 -PropertyType DWord -Force | Out-Null
    }
}
Start-Process -FilePath "cleanmgr.exe" -ArgumentList "/sagerun:99" -Wait -WindowStyle Hidden
Write-Host "✓ Limpeza avançada concluída" -ForegroundColor Green
    Send-Progress 'cleanmgr' 'done' $null
} catch {
    Send-Progress 'cleanmgr' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Limpeza avançada (cleanmgr silencioso, todas as categorias): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- TRIM para SSD / Defrag para HDD (auto-detectado) ---
Send-Progress 'trim' 'running' $null
try {
Write-Host "→ A optimizar discos (TRIM/Defrag)..." -ForegroundColor Yellow
Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter } | ForEach-Object {
    $d = $_.DriveLetter
    Write-Host "   • A optimizar $($d):" -ForegroundColor DarkGray
    Optimize-Volume -DriveLetter $d -ReTrim -Defrag -ErrorAction SilentlyContinue
}
Write-Host "✓ Discos optimizados" -ForegroundColor Green
    Send-Progress 'trim' 'done' $null
} catch {
    Send-Progress 'trim' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em TRIM para SSD / Defrag para HDD (auto-detectado): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "🌐 Rede"

# --- Flush DNS + reset Winsock/TCP ---
Send-Progress 'flushDns' 'running' $null
try {
Write-Host "→ A fazer flush DNS e reset TCP/Winsock..." -ForegroundColor Yellow
ipconfig /flushdns | Out-Null
netsh winsock reset | Out-Null
netsh int ip reset | Out-Null
Write-Host "✓ DNS e stack TCP/IP reiniciados" -ForegroundColor Green
    Send-Progress 'flushDns' 'done' $null
} catch {
    Send-Progress 'flushDns' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Flush DNS + reset Winsock/TCP: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Configurar DNS Cloudflare (1.1.1.1 / 1.0.0.1) ---
Send-Progress 'cfDns' 'running' $null
try {
Write-Host "→ A configurar DNS Cloudflare..." -ForegroundColor Yellow
Get-NetAdapter | Where-Object { $_.Status -eq 'Up' } | ForEach-Object {
    Set-DnsClientServerAddress -InterfaceIndex $_.ifIndex -ServerAddresses ("1.1.1.1","1.0.0.1") -ErrorAction SilentlyContinue
    Write-Host "   • $($_.Name) → 1.1.1.1 / 1.0.0.1" -ForegroundColor DarkGray
}
Write-Host "✓ DNS configurado" -ForegroundColor Green
    Send-Progress 'cfDns' 'done' $null
} catch {
    Send-Progress 'cfDns' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Configurar DNS Cloudflare (1.1.1.1 / 1.0.0.1): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Reduzir latência TCP (desactivar algoritmo de Nagle) ---
Send-Progress 'nagle' 'running' $null
try {
Write-Host "→ A desactivar algoritmo de Nagle..." -ForegroundColor Yellow
$base = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
Get-ChildItem $base | ForEach-Object {
    New-ItemProperty -Path $_.PSPath -Name "TcpAckFrequency" -Value 1 -PropertyType DWord -Force | Out-Null
    New-ItemProperty -Path $_.PSPath -Name "TCPNoDelay" -Value 1 -PropertyType DWord -Force | Out-Null
}
Write-Host "✓ Nagle desactivado" -ForegroundColor Green
    Send-Progress 'nagle' 'done' $null
} catch {
    Send-Progress 'nagle' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Reduzir latência TCP (desactivar algoritmo de Nagle): {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "🔧 Windows Tweaks"

# --- Activar plano de energia Ultimate Performance ---
Send-Progress 'ultimatePower' 'running' $null
try {
Write-Host "→ A activar Ultimate Performance..." -ForegroundColor Yellow
powercfg -duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 | Out-Null
$guid = (powercfg -list | Select-String "Ultimate Performance" | ForEach-Object { ($_ -split '\s+')[3] } | Select-Object -First 1)
if ($guid) { powercfg -setactive $guid }
Write-Host "✓ Plano Ultimate Performance activado" -ForegroundColor Green
    Send-Progress 'ultimatePower' 'done' $null
} catch {
    Send-Progress 'ultimatePower' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Activar plano de energia Ultimate Performance: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Reduzir telemetria ao mínimo ---
Send-Progress 'telemetry' 'running' $null
try {
Write-Host "→ A reduzir telemetria..." -ForegroundColor Yellow
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection" -Name "AllowTelemetry" -Value 0 -Force -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Value 0 -Force -ErrorAction SilentlyContinue
Stop-Service -Name DiagTrack -Force -ErrorAction SilentlyContinue
Set-Service -Name DiagTrack -StartupType Disabled -ErrorAction SilentlyContinue
Write-Host "✓ Telemetria minimizada" -ForegroundColor Green
    Send-Progress 'telemetry' 'done' $null
} catch {
    Send-Progress 'telemetry' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Reduzir telemetria ao mínimo: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Optimizar efeitos visuais para desempenho ---
Send-Progress 'visualFx' 'running' $null
try {
Write-Host "→ A optimizar efeitos visuais..." -ForegroundColor Yellow
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects" -Name "VisualFXSetting" -Value 2 -Force
Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "UserPreferencesMask" -Value ([byte[]](0x90,0x12,0x03,0x80,0x10,0x00,0x00,0x00)) -Force
Write-Host "✓ Efeitos visuais optimizados" -ForegroundColor Green
    Send-Progress 'visualFx' 'done' $null
} catch {
    Send-Progress 'visualFx' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Optimizar efeitos visuais para desempenho: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

# --- Desactivar notificações de background ---
Send-Progress 'bgNotif' 'running' $null
try {
Write-Host "→ A desactivar notificações de background..." -ForegroundColor Yellow
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "ToastEnabled" -Value 0 -Force -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications" -Name "GlobalUserDisabled" -Value 1 -Force -ErrorAction SilentlyContinue
Write-Host "✓ Notificações background desactivadas" -ForegroundColor Green
    Send-Progress 'bgNotif' 'done' $null
} catch {
    Send-Progress 'bgNotif' 'error' $_.Exception.Message
    Write-Host ("✗ Erro em Desactivar notificações de background: {0}" -f $_.Exception.Message) -ForegroundColor Red
}

Write-Section "📊 Sumário"
$fim = Get-SystemState
$discoGanho = [math]::Round($fim.DiscoLivreGB - $inicio.DiscoLivreGB, 2)
$ramGanho = [math]::Round($fim.RAMLivreGB - $inicio.RAMLivreGB, 2)
Write-Host ""
Write-Host ("  Disco livre:  {0} GB  →  {1} GB   ({2:+0.00;-0.00;0} GB)" -f $inicio.DiscoLivreGB, $fim.DiscoLivreGB, $discoGanho) -ForegroundColor White
Write-Host ("  RAM livre:    {0} GB  →  {1} GB   ({2:+0.00;-0.00;0} GB)" -f $inicio.RAMLivreGB, $fim.RAMLivreGB, $ramGanho) -ForegroundColor White
Write-Host ""
Write-Host "  Optimização concluída!" -ForegroundColor Green
Write-Host ""

Send-Progress '_finished' 'done' ("Disco +{0}GB, RAM +{1}GB" -f $discoGanho, $ramGanho)

$resp = Read-Host "Reiniciar agora? (s/n)"
if ($resp -match '^[sSyY]') {
    Write-Host "A reiniciar em 5 segundos..." -ForegroundColor Yellow
    Start-Sleep -Seconds 5
    Restart-Computer -Force
} else {
    Write-Host "OK. Recomenda-se reiniciar mais tarde." -ForegroundColor DarkGray
}