# ========================================== # VERIFICAR ADMINISTRADOR # ========================================== $isAdmin = ([Security.Principal.WindowsPrincipal] ` [Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) if (-not $isAdmin) { Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" exit } Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing # ========================================== # VARIÁVEIS GLOBAIS # ========================================== $botoes = @() $SafeDebloatServices = @( "DiagTrack", # Serviço de Telemetria do Windows "dmwappushservice", # Serviço de Push de Aplicativos do Windows "MapsBroker", # Serviço de Mapas do Windows "fxssvc", # Serviço de Fax do Windows "WpcMonSvc", # Serviço de Monitoramento de Controle dos Pais "XblAuthManager", # Serviço de Autenticação do Xbox Live "XblGameSave", # Serviço de Salvamento de Jogos do Xbox Live "XboxNetApiSvc", # Serviço de API de Rede do Xbox "XboxGipSvc", # Serviço de Plataforma de Jogos do Xbox "wisvc", # Serviço de Experiências do Windows "SysMain", # Serviço de Superfetch do Windows "RetailDemo", # Serviço de Demonstração do Windows "icssvc", # Serviço de Configuração de Conexão Inteligente do Windows "SmsRouter" # Serviço de Roteamento do Windows ) $script:RunspaceAtual = $null $script:PowerShellAtual = $null $script:AsyncAtual = $null $script:TimerExecucao = $null # Fila de mensagens compartilhada $script:FilaLog = [System.Collections.Concurrent.ConcurrentQueue[string]]::new() # ========================================== # SISTEMA DE LOG # ========================================== function Escrever-Log { param ( [string]$Mensagem ) $hora = Get-Date -Format "HH:mm:ss" $logBox.AppendText("[$hora] $Mensagem`r`n") $logBox.SelectionStart = $logBox.Text.Length $logBox.ScrollToCaret() } # ========================================== # FUNÇÃO DE LOG PARA RUNSPACE # ========================================== function Criar-FuncaoLog { return { param([string]$Mensagem) $mensagem = $_.ToString() if ($mensagem -match '^PROGRESSO:(\d+)$') { $fila.Enqueue("PROGRESSO:$($matches[1])") } else { $fila.Enqueue($mensagem) } }.ToString() } # ========================================== # FUNÇÕES DE MANUTENÇÃO # ========================================== function Limpar-Temporarios { Write-Output "Iniciando limpeza de arquivos temporários..." $pastas = @( $env:TEMP, "C:\Windows\Temp" ) foreach ($tempPath in $pastas) { if (Test-Path $tempPath) { Write-Output "Analisando: $tempPath" $arquivos = Get-ChildItem -Path $tempPath -Force -ErrorAction SilentlyContinue Write-Output "Encontrados $($arquivos.Count) itens." Remove-Item -Path "$tempPath\*" -Recurse -Force -ErrorAction SilentlyContinue Write-Output "Limpeza realizada em: $tempPath" } } Write-Output "Limpeza de temporários concluída!" } function Verificar-Sistema { Write-Output "Coletando informações do sistema..." $os = (Get-CimInstance Win32_OperatingSystem).Caption $ram = [math]::Round( (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2 ) Write-Output "Sistema: $os" Write-Output "RAM Total: $ram GB" Write-Output "Computador: $env:COMPUTERNAME" } function Executar-Comando { param ( [string]$Arquivo, [string]$Argumentos ) Write-Output "Executando: $Arquivo $Argumentos" $info = New-Object System.Diagnostics.ProcessStartInfo $info.FileName = $Arquivo $info.Arguments = $Argumentos $info.UseShellExecute = $false $info.RedirectStandardOutput = $true $info.RedirectStandardError = $true $info.CreateNoWindow = $true $processo = New-Object System.Diagnostics.Process $processo.StartInfo = $info try { [void]$processo.Start() # Leitura simultânea das duas saídas $stdout = $processo.StandardOutput.ReadToEndAsync() $stderr = $processo.StandardError.ReadToEndAsync() $processo.WaitForExit() $saida = $stdout.GetAwaiter().GetResult() $erro = $stderr.GetAwaiter().GetResult() if ($saida) { Write-Output $saida } if ($erro) { Write-Output "Saída de erro: $erro" } Write-Output "Código de saída: $($processo.ExitCode)" } finally { $processo.Dispose() } } function Verificar-SFC { Write-Output "Iniciando verificação SFC..." try { # Executa o SFC em um processo separado # sem redirecionar os fluxos de saída. $processo = Start-Process ` -FilePath "$env:windir\System32\sfc.exe" ` -ArgumentList "/scannow" ` -Wait ` -PassThru Write-Output "SFC finalizado." Write-Output "Código de saída: $($processo.ExitCode)" if ($processo.ExitCode -eq 0) { Write-Output "Verificação concluída sem erro de execução." } else { Write-Output "O SFC terminou com código diferente de zero." } } catch { Write-Output "Erro ao executar SFC: $($_.Exception.Message)" } } function Reparar-DISM { Write-Output "Iniciando reparação DISM em modo silencioso (aguarde, pode levar alguns minutos)..." $exitCode = Executar-Comando ` -Arquivo "DISM.exe" ` -Argumentos "/Online /Cleanup-Image /RestoreHealth /Quiet" switch ($exitCode) { 0 { Write-Output "SUCESSO: A imagem do Windows foi verificada e reparada com êxito (Código: 0)." } 3010 { Write-Output "SUCESSO (REINÍCIO NECESSÁRIO): Reparo concluído, mas é necessário reiniciar o computador para aplicar as alterações (Código: 3010)." } 87 { Write-Output "ERRO DE PARÂMETRO: O comando DISM recebeu um argumento inválido (Código: 87)." } 740 { Write-Output "ERRO DE PERMISSÃO: O DISM exige privilégios elevados de Administrador (Código: 740)." } { $_ -in 0x800f081f, -2146498529 } { Write-Output "FALHA DE ORIGEM: Os arquivos de origem do reparo não foram encontrados ou não foi possível baixar do Windows Update (Código: 0x800f081f)." } { $_ -in 0x800f0906, -2146498298 } { Write-Output "FALHA DE REDE: Não foi possível baixar os arquivos de reparo da internet. Verifique a conexão ou proxy (Código: 0x800f0906)." } default { Write-Output "ATENÇÃO: O DISM finalizou com um código inesperado ($exitCode). Consulte o log em C:\Windows\Logs\DISM\dism.log." } } } function Desativar-Servicos { Write-Output "Desativando serviços desnecessários..." foreach ($servico in $SafeDebloatServices) { try { $s = Get-Service -Name $servico -ErrorAction Stop if ($s.Status -ne 'Stopped') { Stop-Service -Name $servico -Force Write-Output "Serviço '$servico' parado." } Set-Service -Name $servico -StartupType Disabled Write-Output "Serviço '$servico' desativado." } catch { Write-Output "Serviço '$servico' não encontrado ou erro ao desativar: $($_.Exception.Message)" } } Write-Output "Desativação de serviços concluída." } function Ativar-Servicos { Write-Output "Ativando serviços desativados..." foreach ($servico in $SafeDebloatServices) { try { $s = Get-Service -Name $servico -ErrorAction Stop Set-Service -Name $servico -StartupType Manual Write-Output "Serviço '$servico' ativado." } catch { Write-Output "Serviço '$servico' não encontrado ou erro ao ativar: $($_.Exception.Message)" } } Write-Output "Ativação de serviços concluída." } # ========================================== # GERENCIADOR DE EXECUÇÃO # ========================================== function Executar-Tarefa { param ( [scriptblock]$Tarefa, [string]$Nome ) if ($script:AsyncAtual -and -not $script:AsyncAtual.IsCompleted) { Escrever-Log "Já existe uma tarefa em execução." return } Escrever-Log "================================" Escrever-Log "Iniciando: $Nome" if ($Nome -eq "Verificação SFC") { $progressBar.Style = "Marquee" $progressBar.MarqueeAnimationSpeed = 25 $lblProgress.Text = "SFC em execução..." } else { $progressBar.Style = "Continuous" $progressBar.Value = 0 $lblProgress.Text = "Executando: $Nome" } foreach ($botao in $botoes) { $botao.Enabled = $false } try { # Cria Runspace $script:RunspaceAtual = [runspacefactory]::CreateRunspace() $script:RunspaceAtual.ApartmentState = "MTA" $script:RunspaceAtual.ThreadOptions = "ReuseThread" $script:RunspaceAtual.Open() # Disponibiliza a fila de log no Runspace $script:RunspaceAtual.SessionStateProxy.SetVariable( "fila", $script:FilaLog ) $script:RunspaceAtual.SessionStateProxy.setVariable( "SafeDebloatServices", $SafeDebloatServices ) # Cria PowerShell independente $script:PowerShellAtual = [powershell]::Create() $script:PowerShellAtual.Runspace = $script:RunspaceAtual # Importa as funções para o Runspace $nomesFuncoes = @( "Limpar-Temporarios", "Verificar-Sistema", "Executar-Comando", "Verificar-SFC", "Desativar-Servicos", "Ativar-Servicos", "Reparar-DISM" ) foreach ($nomeFuncao in $nomesFuncoes) { $codigo = (Get-Item "Function:\$nomeFuncao").ScriptBlock.ToString() $script:PowerShellAtual.AddScript( "function $nomeFuncao { $codigo }" ) | Out-Null } # Redireciona Write-Output para a fila de log $script:PowerShellAtual.AddScript({ param($Codigo) try { & ([scriptblock]::Create($Codigo)) 2>&1 | ForEach-Object { $fila.Enqueue($_.ToString()) } } catch { $fila.Enqueue("ERRO: $($_.Exception.ToString())") } }).AddArgument($Tarefa.ToString()) | Out-Null # Inicia execução $script:AsyncAtual = $script:PowerShellAtual.BeginInvoke() # Timer de monitoramento $script:TimerExecucao = New-Object System.Windows.Forms.Timer $script:TimerExecucao.Interval = 200 $script:TimerExecucao.Add_Tick({ # Atualiza o log com as mensagens recebidas $mensagem = $null while ($script:FilaLog.TryDequeue([ref]$mensagem)) { if ($mensagem -match '^PROGRESSO:(\d+)$') { $percentual = [int]$matches[1] $progressBar.Value = [Math]::Min( 100, [Math]::Max(0, $percentual) ) $lblProgress.Text = "Verificando Windows: $percentual%" } elseif ($mensagem -match '^LOG:(.*)$') { Escrever-Log $matches[1] } else { Escrever-Log $mensagem } } # Verifica conclusão if ($script:AsyncAtual -and $script:AsyncAtual.IsCompleted) { $script:TimerExecucao.Stop() try { $resultado = $script:PowerShellAtual.EndInvoke($script:AsyncAtual) foreach ($item in $resultado) { if ($null -ne $item) { Escrever-Log "$item" } } foreach ($erro in $script:PowerShellAtual.Streams.Error) { Escrever-Log "ERRO: $($erro.ToString())" } } catch { Escrever-Log "Falha: $($_.Exception.ToString())" } finally { # Consome mensagens restantes $mensagem = $null while ($script:FilaLog.TryDequeue([ref]$mensagem)) { Escrever-Log $mensagem } $script:PowerShellAtual.Dispose() $script:RunspaceAtual.Dispose() $script:PowerShellAtual = $null $script:RunspaceAtual = $null $script:AsyncAtual = $null $script:TimerExecucao.Dispose() $script:TimerExecucao = $null foreach ($botao in $botoes) { $botao.Enabled = $true } Escrever-Log "================================" Escrever-Log "Tarefa finalizada." $progressBar.Style = "Continuous" $progressBar.MarqueeAnimationSpeed = 0 $progressBar.Value = 100 $lblProgress.Text = "Operação concluída!" } } }) $script:TimerExecucao.Start() } catch { Escrever-Log "ERRO AO INICIAR:" Escrever-Log $_.Exception.ToString() if ($script:PowerShellAtual) { $script:PowerShellAtual.Dispose() $script:PowerShellAtual = $null } if ($script:RunspaceAtual) { $script:RunspaceAtual.Dispose() $script:RunspaceAtual = $null } $script:AsyncAtual = $null foreach ($botao in $botoes) { $botao.Enabled = $true } } } # ========================================== # CONSTRUÇÃO DA INTERFACE # ========================================== function Atualizar-Progresso { param ( [int]$Percentual, [string]$Mensagem ) if ($Percentual -lt 0) { $Percentual = 0 } if ($Percentual -gt 100) { $Percentual = 100 } $progressBar.Value = $Percentual $lblProgress.Text = "$Mensagem - $Percentual%" } $form = New-Object System.Windows.Forms.Form $form.Text = "Painel de Utilitários" $form.Size = New-Object System.Drawing.Size(480, 480) $form.StartPosition = "CenterScreen" $form.FormBorderStyle = "FixedDialog" $form.MaximizeBox = $false $form.BackColor = [System.Drawing.Color]::FromArgb(30, 30, 30) $form.ForeColor = [System.Drawing.Color]::White # ========================================== # FUNÇÃO CRIAR BOTÃO # ========================================== function Criar-Botao { param ( [string]$Texto, [int]$X, [int]$Y, [System.Drawing.Color]$Cor, [scriptblock]$Acao ) $botao = New-Object System.Windows.Forms.Button $botao.Text = $Texto $botao.Size = New-Object System.Drawing.Size(190, 38) $botao.Location = New-Object System.Drawing.Point($X, $Y) $botao.BackColor = $Cor $botao.ForeColor = [System.Drawing.Color]::White $botao.FlatStyle = "Flat" $botao.Add_Click($Acao) $form.Controls.Add($botao) $script:botoes += $botao } # ========================================== # BOTÕES # ========================================== # Limpar Temp Criar-Botao ` -Texto "Limpar Temp" ` -X 25 -Y 20 ` -Cor ([System.Drawing.Color]::FromArgb(0, 120, 215)) ` -Acao { Executar-Tarefa -Nome "Limpeza TEMP" -Tarefa { Limpar-Temporarios } } # Info do Sistema Criar-Botao ` -Texto "Info do Sistema" ` -X 245 -Y 20 ` -Cor ([System.Drawing.Color]::FromArgb(45, 130, 80)) ` -Acao { Executar-Tarefa -Nome "Informações do Sistema" -Tarefa { Verificar-Sistema } } # SFC / Scannow Criar-Botao ` -Texto "SFC / Scannow" ` -X 25 -Y 70 ` -Cor ([System.Drawing.Color]::FromArgb(150, 90, 35)) ` -Acao { Executar-Tarefa -Nome "Verificação SFC" -Tarefa { Verificar-SFC } } # Reparar DISM Criar-Botao ` -Texto "Reparar DISM" ` -X 245 -Y 70 ` -Cor ([System.Drawing.Color]::FromArgb(120, 65, 150)) ` -Acao { Executar-Tarefa -Nome "Reparação DISM" -Tarefa { Reparar-DISM } } # Desativar / Ativar Serviços Criar-Botao ` -Texto "Desativar Serviços" ` -X 25 -Y 120 ` -Cor ([System.Drawing.Color]::FromArgb(200, 50, 50)) ` -Acao { Executar-Tarefa -Nome "Desativação de Serviços" -Tarefa { Desativar-Servicos } } # Ativar Serviços Criar-Botao ` -Texto "Ativar Serviços" ` -X 245 -Y 120 ` -Cor ([System.Drawing.Color]::FromArgb(50, 200, 50)) ` -Acao { Executar-Tarefa -Nome "Ativação de Serviços" -Tarefa { Ativar-Servicos } } # ========================================== # LOG # ========================================== $logBox = New-Object System.Windows.Forms.TextBox $logBox.Multiline = $true $logBox.ScrollBars = "Vertical" $logBox.ReadOnly = $true $logBox.WordWrap = $true $logBox.Font = New-Object System.Drawing.Font("Consolas", 9) $logBox.BackColor = [System.Drawing.Color]::FromArgb(20, 20, 20) $logBox.ForeColor = [System.Drawing.Color]::LightGreen $logBox.Size = New-Object System.Drawing.Size(410, 245) $logBox.Location = New-Object System.Drawing.Point(25, 175) $form.Controls.Add($logBox) # ========================================== # BARRA DE PROGRESSO # ========================================== $progressBar = New-Object System.Windows.Forms.ProgressBar $progressBar.Size = New-Object System.Drawing.Size(410, 22) $progressBar.Location = New-Object System.Drawing.Point(25, 430) $progressBar.Minimum = 0 $progressBar.Maximum = 100 $progressBar.Value = 0 $progressBar.Style = "Continuous" $form.Controls.Add($progressBar) # Texto do percentual $lblProgress = New-Object System.Windows.Forms.Label $lblProgress.Text = "Aguardando operação..." $lblProgress.Size = New-Object System.Drawing.Size(410, 20) $lblProgress.Location = New-Object System.Drawing.Point(25, 455) $lblProgress.ForeColor = [System.Drawing.Color]::White $form.Controls.Add($lblProgress) $form.Size = New-Object System.Drawing.Size(480, 525) # ========================================== # ENCERRAMENTO SEGURO # ========================================== $form.Add_FormClosing({ if ($script:AsyncAtual -and -not $script:AsyncAtual.IsCompleted) { $resposta = [System.Windows.Forms.MessageBox]::Show( "Existe uma tarefa em execução. Deseja realmente fechar o painel?", "Confirmação", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Warning ) if ($resposta -eq [System.Windows.Forms.DialogResult]::No) { $_.Cancel = $true } } }) # ========================================== # INICIAR # ========================================== Escrever-Log "Painel de Utilitários iniciado." Escrever-Log "Aguardando operação..." [void]$form.ShowDialog()