# Script de Verificação e Correção Automática do NoIdle # Este script verifica se o NoIdle está configurado e funcionando corretamente # E corrige automaticamente qualquer problema encontrado # Uso: .\VERIFICAR_E_CORRIGIR_NOIDLE.ps1 param( [switch]$AutoFix ) $AppName = "NoIdle" $TaskName = "NoIdle_Monitor" $InstallDir = "$env:ProgramFiles\$AppName" $ExePath = "$InstallDir\NoIdle.exe" $ConfigPath = "$env:APPDATA\$AppName\config.json" $RegKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" $ApiUrl = "https://admin.noidle.tech" $problemsFound = @() $warningsFound = @() Write-Host "========================================" -ForegroundColor Cyan Write-Host "NoIdle - Diagnóstico e Correção" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan Write-Host "" # ============================================ # 1. VERIFICAR INSTALAÇÃO # ============================================ Write-Host "[ 1/8 ] Verificando instalação..." -ForegroundColor Yellow if (Test-Path $ExePath) { Write-Host " ✅ Executável encontrado: $ExePath" -ForegroundColor Green $fileInfo = Get-Item $ExePath Write-Host " Tamanho: $([math]::Round($fileInfo.Length / 1MB, 2)) MB | Modificado: $($fileInfo.LastWriteTime)" -ForegroundColor Gray } else { Write-Host " ❌ ERRO: Executável não encontrado!" -ForegroundColor Red $problemsFound += "Executável não instalado em $ExePath" } Write-Host "" # ============================================ # 2. VERIFICAR CONFIGURAÇÃO # ============================================ Write-Host "[ 2/8 ] Verificando configuração..." -ForegroundColor Yellow if (Test-Path $ConfigPath) { Write-Host " ✅ Arquivo de configuração encontrado" -ForegroundColor Green try { $config = Get-Content $ConfigPath | ConvertFrom-Json if ($config.device_id) { Write-Host " ✅ Device ID configurado: $($config.device_id)" -ForegroundColor Green } else { Write-Host " ❌ Device ID não encontrado na configuração" -ForegroundColor Red $problemsFound += "Device ID não configurado" } } catch { Write-Host " ⚠️ Erro ao ler configuração: $_" -ForegroundColor Yellow $warningsFound += "Arquivo de configuração corrompido" } } else { Write-Host " ⚠️ Arquivo de configuração não encontrado" -ForegroundColor Yellow Write-Host " (Será criado na primeira execução)" -ForegroundColor Gray $warningsFound += "Arquivo de configuração não existe (normal em primeira instalação)" } Write-Host "" # ============================================ # 3. VERIFICAR PROCESSO # ============================================ Write-Host "[ 3/8 ] Verificando se está em execução..." -ForegroundColor Yellow $runningProcess = Get-Process -Name "NoIdle" -ErrorAction SilentlyContinue if ($runningProcess) { Write-Host " ✅ NoIdle está em execução (PID: $($runningProcess.Id))" -ForegroundColor Green Write-Host " Tempo de execução: $((Get-Date) - $runningProcess.StartTime)" -ForegroundColor Gray } else { Write-Host " ❌ NoIdle NÃO está em execução" -ForegroundColor Red $problemsFound += "Processo não está rodando" } Write-Host "" # ============================================ # 4. VERIFICAR AUTO-START (REGISTRY) # ============================================ Write-Host "[ 4/8 ] Verificando auto-start (Registro)..." -ForegroundColor Yellow try { $regValue = Get-ItemProperty -Path $RegKey -Name $AppName -ErrorAction SilentlyContinue if ($regValue) { $regCommand = $regValue.$AppName Write-Host " ✅ Registro configurado" -ForegroundColor Green Write-Host " Comando: $regCommand" -ForegroundColor Gray # Verificar se tem --silent if ($regCommand -notlike "*--silent*") { Write-Host " ⚠️ AVISO: Comando não inclui --silent" -ForegroundColor Yellow $warningsFound += "Registro não está usando modo silencioso" } # Verificar se o caminho está correto if ($regCommand -notlike "*$ExePath*") { Write-Host " ⚠️ AVISO: Caminho no registro não corresponde ao instalado" -ForegroundColor Yellow $warningsFound += "Caminho no registro está incorreto" } } else { Write-Host " ❌ Registro NÃO configurado" -ForegroundColor Red $problemsFound += "Auto-start não configurado no Registro" } } catch { Write-Host " ❌ Erro ao verificar registro: $_" -ForegroundColor Red $problemsFound += "Erro ao acessar Registro" } Write-Host "" # ============================================ # 5. VERIFICAR AUTO-START (TASK SCHEDULER) # ============================================ Write-Host "[ 5/8 ] Verificando auto-start (Task Scheduler)..." -ForegroundColor Yellow try { $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if ($task) { $taskState = $task.State $taskEnabled = $task.State -ne "Disabled" if ($taskEnabled) { Write-Host " ✅ Task Scheduler configurado e ativo" -ForegroundColor Green } else { Write-Host " ⚠️ Task Scheduler configurado mas DESABILITADO" -ForegroundColor Yellow $warningsFound += "Task Scheduler está desabilitado" } Write-Host " Nome: $TaskName | Estado: $taskState" -ForegroundColor Gray # Verificar última execução $taskInfo = Get-ScheduledTaskInfo -TaskName $TaskName -ErrorAction SilentlyContinue if ($taskInfo.LastRunTime) { Write-Host " Última execução: $($taskInfo.LastRunTime)" -ForegroundColor Gray } } else { Write-Host " ⚠️ Task Scheduler NÃO configurado" -ForegroundColor Yellow $warningsFound += "Task Scheduler não configurado (Registry será usado)" } } catch { Write-Host " ⚠️ Erro ao verificar Task Scheduler: $_" -ForegroundColor Yellow $warningsFound += "Erro ao acessar Task Scheduler" } Write-Host "" # ============================================ # 6. VERIFICAR CONECTIVIDADE COM API # ============================================ Write-Host "[ 6/8 ] Verificando conectividade com API..." -ForegroundColor Yellow try { $testUrl = "$ApiUrl/api/devices/heartbeat" $testData = @{ device_id = "TEST" } | ConvertTo-Json $response = Invoke-WebRequest ` -Uri $testUrl ` -Method POST ` -Body $testData ` -ContentType "application/json" ` -TimeoutSec 10 ` -ErrorAction Stop Write-Host " ✅ API acessível (Status: $($response.StatusCode))" -ForegroundColor Green Write-Host " URL: $ApiUrl" -ForegroundColor Gray } catch { Write-Host " ❌ Não foi possível conectar à API" -ForegroundColor Red Write-Host " Erro: $($_.Exception.Message)" -ForegroundColor Gray $problemsFound += "Sem conectividade com a API" } Write-Host "" # ============================================ # 7. VERIFICAR FIREWALL # ============================================ Write-Host "[ 7/8 ] Verificando Firewall..." -ForegroundColor Yellow $firewallRules = Get-NetFirewallRule | Where-Object { $_.DisplayName -like "*NoIdle*" } if ($firewallRules) { $enabledRules = $firewallRules | Where-Object { $_.Enabled -eq $true } Write-Host " ✅ Regras de firewall encontradas: $($firewallRules.Count)" -ForegroundColor Green Write-Host " Ativas: $($enabledRules.Count)" -ForegroundColor Gray } else { Write-Host " ⚠️ Nenhuma regra de firewall específica" -ForegroundColor Yellow Write-Host " (Isso é normal, mas pode causar problemas se o firewall estiver restritivo)" -ForegroundColor Gray } Write-Host "" # ============================================ # 8. VERIFICAR LOGS/ERROS RECENTES # ============================================ Write-Host "[ 8/8 ] Verificando logs do sistema..." -ForegroundColor Yellow try { $appErrors = Get-EventLog -LogName Application -Source "NoIdle*" -Newest 10 -ErrorAction SilentlyContinue if ($appErrors) { $errors = $appErrors | Where-Object { $_.EntryType -eq "Error" } if ($errors) { Write-Host " ⚠️ Erros encontrados nos logs: $($errors.Count)" -ForegroundColor Yellow $warningsFound += "Erros no log de eventos" } else { Write-Host " ✅ Sem erros recentes nos logs" -ForegroundColor Green } } else { Write-Host " ℹ️ Nenhum log do NoIdle encontrado" -ForegroundColor Gray } } catch { Write-Host " ℹ️ Não foi possível verificar logs" -ForegroundColor Gray } Write-Host "" # ============================================ # RESUMO # ============================================ Write-Host "========================================" -ForegroundColor Cyan Write-Host "RESUMO DO DIAGNÓSTICO" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan Write-Host "" if ($problemsFound.Count -eq 0 -and $warningsFound.Count -eq 0) { Write-Host "✅ TUDO OK! Nenhum problema encontrado." -ForegroundColor Green Write-Host "" Write-Host "O NoIdle está configurado e funcionando corretamente." -ForegroundColor Green } else { if ($problemsFound.Count -gt 0) { Write-Host "❌ PROBLEMAS CRÍTICOS ENCONTRADOS:" -ForegroundColor Red foreach ($problem in $problemsFound) { Write-Host " • $problem" -ForegroundColor Red } Write-Host "" } if ($warningsFound.Count -gt 0) { Write-Host "⚠️ AVISOS:" -ForegroundColor Yellow foreach ($warning in $warningsFound) { Write-Host " • $warning" -ForegroundColor Yellow } Write-Host "" } } # ============================================ # CORREÇÃO AUTOMÁTICA # ============================================ if ($problemsFound.Count -gt 0) { Write-Host "========================================" -ForegroundColor Yellow Write-Host "CORREÇÃO AUTOMÁTICA" -ForegroundColor Yellow Write-Host "========================================" -ForegroundColor Yellow Write-Host "" $shouldFix = $AutoFix if (-not $shouldFix) { $resposta = Read-Host "Deseja tentar corrigir os problemas automaticamente? (S/N)" $shouldFix = ($resposta -eq "S" -or $resposta -eq "s") } if ($shouldFix) { Write-Host "Iniciando correções..." -ForegroundColor Cyan Write-Host "" # Corrigir auto-start no Registry if ($problemsFound -contains "Auto-start não configurado no Registro" -or $warningsFound -contains "Registro não está usando modo silencioso" -or $warningsFound -contains "Caminho no registro está incorreto") { Write-Host "Corrigindo Registro do Windows..." -ForegroundColor Cyan try { $registryValue = "`"$ExePath`" --silent" Set-ItemProperty -Path $RegKey -Name $AppName -Value $registryValue -Type String -Force Write-Host "✅ Registro corrigido" -ForegroundColor Green } catch { Write-Host "❌ Erro ao corrigir registro: $_" -ForegroundColor Red } Write-Host "" } # Corrigir Task Scheduler if ($warningsFound -contains "Task Scheduler não configurado (Registry será usado)" -or $warningsFound -contains "Task Scheduler está desabilitado") { Write-Host "Configurando Task Scheduler..." -ForegroundColor Cyan try { # Remover tarefa existente se houver Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue | Out-Null # Criar nova tarefa $action = New-ScheduledTaskAction -Execute "`"$ExePath`"" -Argument '--silent' $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited $settings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries ` -DontStopIfGoingOnBatteries ` -StartWhenAvailable ` -RestartCount 3 ` -RestartInterval (New-TimeSpan -Minutes 1) ` -ExecutionTimeLimit (New-TimeSpan -Days 0) Register-ScheduledTask ` -TaskName $TaskName ` -Action $action ` -Trigger $trigger ` -Principal $principal ` -Settings $settings ` -Description "Monitora atividades do usuário para o sistema NoIdle" ` -Force | Out-Null Write-Host "✅ Task Scheduler configurado" -ForegroundColor Green } catch { Write-Host "⚠️ Erro ao configurar Task Scheduler: $_" -ForegroundColor Yellow } Write-Host "" } # Iniciar processo se não estiver rodando if ($problemsFound -contains "Processo não está rodando") { Write-Host "Iniciando NoIdle..." -ForegroundColor Cyan try { Start-Process -FilePath $ExePath -ArgumentList "--silent" -WindowStyle Hidden Start-Sleep -Seconds 2 $checkProcess = Get-Process -Name "NoIdle" -ErrorAction SilentlyContinue if ($checkProcess) { Write-Host "✅ NoIdle iniciado com sucesso (PID: $($checkProcess.Id))" -ForegroundColor Green } else { Write-Host "⚠️ NoIdle foi iniciado mas não aparece nos processos" -ForegroundColor Yellow } } catch { Write-Host "❌ Erro ao iniciar NoIdle: $_" -ForegroundColor Red } Write-Host "" } Write-Host "========================================" -ForegroundColor Green Write-Host "✅ Correções aplicadas!" -ForegroundColor Green Write-Host "========================================" -ForegroundColor Green Write-Host "" Write-Host "Recomendações:" -ForegroundColor Cyan Write-Host "1. Reinicie o computador para testar o auto-start" -ForegroundColor White Write-Host "2. Execute este script novamente após o reboot para verificar" -ForegroundColor White Write-Host "" } else { Write-Host "Correção cancelada. Execute novamente com -AutoFix para corrigir automaticamente." -ForegroundColor Yellow } } Write-Host ""