<# ============================================================ PSC TOOLKIT - Bancada Tecnica Pro Service Computer ============================================================ Uso (PowerShell): irm https://portal.proservicecomputer.pt/bancada/ | iex Contacto : Tlm 914 104 710 | geral@proservicecomputer.pt Web : proservicecomputer.pt (Cascais / Lisboa) Notas de engenharia: - Ficheiro propositadamente em ASCII puro (sem acentos) para evitar problemas de codificacao via irm | iex no PowerShell 5.1. - Comandos nativos correm via Start-Process -NoNewWindow para que o output UTF-16 do SFC/DISM apareca correto na consola. - Todas as acoes ficam registadas em C:\PSC\Logs\ ============================================================ #> $script:PSCSelfPath = $MyInvocation.MyCommand.Path function Start-PSCToolkit { # ------------------------------------------------------------ # Configuracao # ------------------------------------------------------------ $script:PSC = @{ Version = '2.4.0' Url = 'https://portal.proservicecomputer.pt/bancada/' UploadUrl = 'https://portal.proservicecomputer.pt/bancada/upload_log.php' LogDir = 'C:\PSC\Logs' } # ------------------------------------------------------------ # Elevacao + forcar Windows PowerShell 5.1 (Checkpoint-Computer) # ------------------------------------------------------------ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator) $isCore = $PSVersionTable.PSEdition -eq 'Core' if (-not $isAdmin -or $isCore) { Write-Host '' Write-Host ' [PSC] A reabrir como Administrador em Windows PowerShell...' -ForegroundColor Yellow if ($script:PSCSelfPath) { $argList = "-NoProfile -ExecutionPolicy Bypass -File `"$($script:PSCSelfPath)`"" } else { $argList = "-NoProfile -ExecutionPolicy Bypass -Command `"[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; irm $($script:PSC.Url) | iex`"" } try { Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $argList -ErrorAction Stop } catch { Write-Host ' [PSC] Elevacao cancelada ou falhada. O toolkit requer Administrador.' -ForegroundColor Red } return } # ------------------------------------------------------------ # Preparacao da sessao # ------------------------------------------------------------ if (-not (Test-Path $script:PSC.LogDir)) { New-Item -Path $script:PSC.LogDir -ItemType Directory -Force | Out-Null } $script:LogFile = Join-Path $script:PSC.LogDir ("PSC-Toolkit_{0}_{1}.log" -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd_HHmmss')) $Host.UI.RawUI.WindowTitle = "PSC Toolkit v$($script:PSC.Version) - Pro Service Computer" $script:SysInfo = Get-PSCSystemInfo Write-Log "Sessao iniciada | $($env:COMPUTERNAME) | $($script:SysInfo.OS) | Utilizador: $env:USERNAME" Show-MainMenu Write-Log 'Sessao terminada' Write-Host '' Write-Host " Log da sessao: $($script:LogFile)" -ForegroundColor DarkGray Write-Host ' Obrigado - Pro Service Computer | 914 104 710' -ForegroundColor DarkYellow Write-Host '' } # ================================================================ # UTILITARIOS BASE # ================================================================ function Write-Log { param([string]$Message, [ValidateSet('INFO', 'OK', 'WARN', 'ERROR')][string]$Level = 'INFO') $line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message try { Add-Content -Path $script:LogFile -Value $line -Encoding UTF8 } catch { } } function Write-Ok { param([string]$m) Write-Host " [OK] $m" -ForegroundColor Green; Write-Log $m 'OK' } function Write-Warn { param([string]$m) Write-Host " [!] $m" -ForegroundColor Yellow; Write-Log $m 'WARN' } function Write-Err { param([string]$m) Write-Host " [ERRO] $m" -ForegroundColor Red; Write-Log $m 'ERROR' } function Write-Info { param([string]$m) Write-Host " [i] $m" -ForegroundColor Cyan; Write-Log $m 'INFO' } function Write-Section { param([string]$Title) Write-Host '' Write-Host ' ------------------------------------------------------------' -ForegroundColor DarkYellow Write-Host " $Title" -ForegroundColor White Write-Host ' ------------------------------------------------------------' -ForegroundColor DarkYellow } function Read-Choice { param([string]$Prompt = 'Escolha uma opcao') Write-Host '' $r = Read-Host " $Prompt" if ($null -eq $r) { return '' } return $r.Trim().ToUpper() } function Confirm-Action { param([string]$Question) $r = Read-Choice "$Question (S/N)" return ($r -eq 'S' -or $r -eq 'Y') } function Wait-Return { Write-Host '' Read-Host ' Prima ENTER para voltar ao menu' | Out-Null } function Invoke-Native { <# Corre um executavel nativo diretamente na consola e devolve o exit code. #> param([string]$FilePath, [string]$Arguments) Write-Host " > $FilePath $Arguments" -ForegroundColor DarkGray Write-Log "CMD: $FilePath $Arguments" try { $p = Start-Process -FilePath $FilePath -ArgumentList $Arguments -NoNewWindow -Wait -PassThru -ErrorAction Stop Write-Log "EXIT: $($p.ExitCode) ($FilePath)" return $p.ExitCode } catch { Write-Err "Falha ao executar $FilePath : $($_.Exception.Message)" return -1 } } function Test-PendingReboot { $keys = @( 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending', 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' ) foreach ($k in $keys) { if (Test-Path $k) { return $true } } $pfro = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name PendingFileRenameOperations -ErrorAction SilentlyContinue return [bool]$pfro } function Get-PSCSystemInfo { $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue $cv = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction SilentlyContinue $ver = if ($cv.DisplayVersion) { $cv.DisplayVersion } else { $cv.ReleaseId } $caption = if ($os) { $os.Caption -replace '^Microsoft\s+', '' } else { 'Windows' } $sysDrive = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'" -ErrorAction SilentlyContinue $free = if ($sysDrive) { '{0:N1} GB livres de {1:N0} GB' -f ($sysDrive.FreeSpace / 1GB), ($sysDrive.Size / 1GB) } else { 'n/d' } [pscustomobject]@{ OS = "$caption $ver (build $($os.BuildNumber).$($cv.UBR))" Build = [int]$os.BuildNumber Disk = "$env:SystemDrive $free" } } function Show-Header { Clear-Host Write-Host '' Write-Host ' ============================================================' -ForegroundColor DarkYellow Write-Host " PSC TOOLKIT v$($script:PSC.Version) | Pro Service Computer" -ForegroundColor White Write-Host ' Tlm: 914 104 710 | proservicecomputer.pt' -ForegroundColor Gray Write-Host ' ============================================================' -ForegroundColor DarkYellow Write-Host " Maquina : $env:COMPUTERNAME" -ForegroundColor Gray Write-Host " Sistema : $($script:SysInfo.OS)" -ForegroundColor Gray Write-Host " Disco : $($script:SysInfo.Disk)" -ForegroundColor Gray if (Test-PendingReboot) { Write-Host ' Estado : REINICIO PENDENTE - recomenda-se reiniciar antes de reparar' -ForegroundColor Yellow } Write-Host ' ============================================================' -ForegroundColor DarkYellow } function Write-MenuItem { param([string]$Key, [string]$Text, [switch]$Soon, [switch]$Recommended) Write-Host " [" -NoNewline -ForegroundColor DarkGray Write-Host $Key -NoNewline -ForegroundColor DarkYellow Write-Host "] " -NoNewline -ForegroundColor DarkGray if ($Soon) { Write-Host $Text -NoNewline -ForegroundColor DarkGray Write-Host ' (em breve)' -ForegroundColor DarkGray } elseif ($Recommended) { Write-Host $Text -NoNewline -ForegroundColor White Write-Host ' * recomendado' -ForegroundColor Green } else { Write-Host $Text -ForegroundColor White } } # ================================================================ # PONTO DE RESTAURO # ================================================================ function New-PSCRestorePoint { param([string]$Description = 'PSC Toolkit - antes de reparacao') Write-Info 'A criar ponto de restauro do sistema...' $key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore' $old = (Get-ItemProperty $key -Name SystemRestorePointCreationFrequency -ErrorAction SilentlyContinue).SystemRestorePointCreationFrequency try { Enable-ComputerRestore -Drive "$env:SystemDrive\" -ErrorAction Stop # Remove temporariamente o limite de 1 ponto por 24h Set-ItemProperty -Path $key -Name SystemRestorePointCreationFrequency -Value 0 -Type DWord -ErrorAction Stop Checkpoint-Computer -Description $Description -RestorePointType MODIFY_SETTINGS -ErrorAction Stop Write-Ok "Ponto de restauro criado: $Description" return $true } catch { Write-Warn "Nao foi possivel criar ponto de restauro: $($_.Exception.Message)" return $false } finally { if ($null -eq $old) { Remove-ItemProperty -Path $key -Name SystemRestorePointCreationFrequency -ErrorAction SilentlyContinue } else { Set-ItemProperty -Path $key -Name SystemRestorePointCreationFrequency -Value $old -Type DWord -ErrorAction SilentlyContinue } } } function Confirm-RestorePoint { if (Confirm-Action 'Criar ponto de restauro antes de continuar? (recomendado)') { [void](New-PSCRestorePoint) } } # ================================================================ # MODULO 1 - REPARACAO DO S.O. # ================================================================ function Invoke-SFC { Write-Section 'SFC - Verificador de Ficheiros de Sistema' Write-Info 'Pode demorar 10-30 minutos. Nao feche esta janela.' $code = Invoke-Native 'sfc.exe' '/scannow' # Extrai as linhas [SR] do CBS.log para o log da sessao $cbs = Join-Path $env:windir 'Logs\CBS\CBS.log' if (Test-Path $cbs) { $out = Join-Path $script:PSC.LogDir ("SFC-detalhes_{0}.txt" -f (Get-Date -Format 'yyyyMMdd_HHmmss')) try { Select-String -Path $cbs -Pattern '\[SR\]' -ErrorAction Stop | ForEach-Object { $_.Line } | Set-Content -Path $out -Encoding UTF8 Write-Info "Detalhes SFC exportados: $out" } catch { Write-Warn 'CBS.log em uso - detalhes SFC nao exportados.' } } if ($code -eq 0) { Write-Ok 'SFC concluido.' } else { Write-Warn "SFC terminou com codigo $code - ver mensagem acima." } return $code } function Invoke-DismScan { Write-Section 'DISM - Verificar estado da imagem (ScanHealth)' $code = Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /ScanHealth' if ($code -eq 0) { Write-Ok 'ScanHealth concluido.' } else { Write-Warn "ScanHealth terminou com codigo $code." } return $code } function Invoke-DismRestore { Write-Section 'DISM - Reparar imagem (RestoreHealth via Windows Update)' Write-Info 'Requer ligacao a Internet. Pode parecer parado nos 20%/62% - e normal.' $code = Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /RestoreHealth' if ($code -eq 0) { Write-Ok 'Imagem do Windows reparada / saudavel.' } else { Write-Warn "RestoreHealth falhou (codigo $code). Tente a opcao de reparacao via ISO/USB." } return $code } function Invoke-DismFromMedia { Write-Section 'DISM - Reparar a partir de ISO / USB de instalacao' Write-Info 'Monte a ISO (duplo clique) ou ligue a pen com a MESMA versao/idioma do Windows.' $images = @() foreach ($d in (Get-PSDrive -PSProvider FileSystem -ErrorAction SilentlyContinue)) { foreach ($n in 'install.wim', 'install.esd') { $p = Join-Path $d.Root "sources\$n" if (Test-Path $p) { $images += $p } } } if ($images.Count -eq 0) { Write-Warn 'Nenhum install.wim / install.esd encontrado. Monte a ISO e tente novamente.' return -1 } $img = $images[0] if ($images.Count -gt 1) { for ($i = 0; $i -lt $images.Count; $i++) { Write-MenuItem ($i + 1) $images[$i] } $sel = Read-Choice 'Qual a imagem a usar' if ($sel -notmatch '^\d+$' -or [int]$sel -lt 1 -or [int]$sel -gt $images.Count) { Write-Warn 'Opcao invalida.'; return -1 } $img = $images[[int]$sel - 1] } Write-Info "Imagem: $img" try { $editions = Get-WindowsImage -ImagePath $img -ErrorAction Stop } catch { Write-Err "Nao foi possivel ler a imagem: $($_.Exception.Message)"; return -1 } $currentEdition = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').EditionID Write-Host '' Write-Host " Edicao instalada nesta maquina: $currentEdition" -ForegroundColor Cyan foreach ($e in $editions) { Write-MenuItem $e.ImageIndex $e.ImageName } $idx = Read-Choice 'Indice da edicao correspondente' if ($idx -notmatch '^\d+$' -or -not ($editions | Where-Object { $_.ImageIndex -eq [int]$idx })) { Write-Warn 'Indice invalido.' return -1 } $type = if ($img -like '*.esd') { 'esd' } else { 'wim' } $source = '{0}:{1}:{2}' -f $type, $img, $idx $code = Invoke-Native 'DISM.exe' "/Online /Cleanup-Image /RestoreHealth /Source:$source /LimitAccess" if ($code -eq 0) { Write-Ok 'Imagem reparada a partir do suporte de instalacao.' } else { Write-Warn "Falhou (codigo $code). Confirme que a ISO e da mesma build/idioma." } return $code } function Get-YesKey { <# Tecla "Sim" das perguntas do chkdsk, conforme o idioma do Windows. #> switch ((Get-UICulture).TwoLetterISOLanguageName) { { $_ -in 'pt', 'es', 'it' } { return 'S' } 'fr' { return 'O' } 'de' { return 'J' } default { return 'Y' } } } function Invoke-ChkdskMenu { Write-Section "CHKDSK - Disco do sistema ($env:SystemDrive)" Write-MenuItem '1' 'Analise online (sem reiniciar, rapido)' -Recommended Write-MenuItem '2' 'Agendar reparacao /f no proximo arranque' Write-MenuItem '3' 'Agendar reparacao completa /f /r (demorado - setores defeituosos)' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { $code = Invoke-Native 'chkdsk.exe' "$env:SystemDrive /scan" if ($code -eq 0) { Write-Ok 'Nenhum problema encontrado no sistema de ficheiros.' } else { Write-Warn "CHKDSK reportou problemas (codigo $code). Considere agendar /f." } } '2' { [void](Invoke-Native 'cmd.exe' "/c echo $(Get-YesKey)| chkdsk $env:SystemDrive /f") Write-Info 'Se a pergunta foi aceite, o CHKDSK /f corre no proximo reinicio.' } '3' { Write-Warn 'A opcao /r pode demorar horas em discos grandes/HDD.' if (Confirm-Action 'Confirmar agendamento de CHKDSK /f /r?') { [void](Invoke-Native 'cmd.exe' "/c echo $(Get-YesKey)| chkdsk $env:SystemDrive /f /r") Write-Info 'Se a pergunta foi aceite, o CHKDSK /f /r corre no proximo reinicio.' } } } } function Reset-WindowsUpdate { Write-Section 'Reset dos componentes do Windows Update' Write-Info 'Para servicos, renomeia SoftwareDistribution e catroot2 (com backup) e reinicia servicos.' if (-not (Confirm-Action 'Continuar?')) { return } $services = 'wuauserv', 'bits', 'cryptsvc', 'msiserver', 'usosvc' foreach ($s in $services) { if (Get-Service -Name $s -ErrorAction SilentlyContinue) { Stop-Service -Name $s -Force -ErrorAction SilentlyContinue Write-Info "Servico parado: $s" } } Start-Sleep -Seconds 2 $stamp = Get-Date -Format 'yyyyMMdd_HHmmss' $folders = @( (Join-Path $env:windir 'SoftwareDistribution'), (Join-Path $env:windir 'System32\catroot2') ) foreach ($f in $folders) { if (Test-Path $f) { try { Rename-Item -Path $f -NewName ("{0}.psc_{1}" -f (Split-Path $f -Leaf), $stamp) -ErrorAction Stop Write-Ok "Renomeado: $f" } catch { Write-Err "Nao foi possivel renomear $f : $($_.Exception.Message)" } } } # Limpa fila do BITS $qmgr = Join-Path $env:ALLUSERSPROFILE 'Microsoft\Network\Downloader' Get-ChildItem -Path $qmgr -Filter 'qmgr*.dat' -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue foreach ($s in 'cryptsvc', 'bits', 'wuauserv', 'msiserver') { Start-Service -Name $s -ErrorAction SilentlyContinue } Write-Ok 'Windows Update reposto. Execute uma nova pesquisa de atualizacoes.' Write-Info "As pastas antigas (*.psc_$stamp) podem ser apagadas apos confirmar que o WU funciona." } function Reset-Network { Write-Section 'Reset de rede (Winsock / TCP-IP / DNS)' Write-Warn 'ATENCAO: IPs estaticos configurados nos adaptadores podem ser perdidos.' Write-Info 'A configuracao atual (ipconfig /all) sera guardada nos logs antes do reset.' if (-not (Confirm-Action 'Continuar?')) { return } $backup = Join-Path $script:PSC.LogDir ("ipconfig-antes-reset_{0}.txt" -f (Get-Date -Format 'yyyyMMdd_HHmmss')) & ipconfig.exe /all | Out-File -FilePath $backup -Encoding UTF8 Write-Ok "Configuracao de rede guardada: $backup" [void](Invoke-Native 'ipconfig.exe' '/flushdns') [void](Invoke-Native 'netsh.exe' 'winsock reset') [void](Invoke-Native 'netsh.exe' 'int ip reset') [void](Invoke-Native 'netsh.exe' 'int ipv6 reset') [void](Invoke-Native 'netsh.exe' 'winhttp reset proxy') Write-Ok 'Reset de rede concluido. E NECESSARIO REINICIAR o computador.' } function Repair-WMI { Write-Section 'Reparar repositorio WMI' $code = Invoke-Native 'winmgmt.exe' '/verifyrepository' if ($code -eq 0) { Write-Ok 'Repositorio WMI consistente (codigo 0).' if (-not (Confirm-Action 'Forcar salvage mesmo assim?')) { return } } else { Write-Warn "Repositorio WMI possivelmente inconsistente (codigo $code)." if (-not (Confirm-Action 'Executar winmgmt /salvagerepository?')) { return } } $code = Invoke-Native 'winmgmt.exe' '/salvagerepository' if ($code -eq 0) { Write-Ok 'Repositorio WMI recuperado.' } else { Write-Err "Salvage falhou (codigo $code). Ultimo recurso: winmgmt /resetrepository (manual)." } } function Repair-StoreApps { Write-Section 'Reparar Microsoft Store / Apps' Write-MenuItem '1' 'Limpar cache da Store (wsreset)' -Recommended Write-MenuItem '2' 'Re-registar a Microsoft Store' Write-MenuItem '3' 'Re-registar TODAS as apps do sistema (demorado, gera avisos)' Write-MenuItem '0' 'Voltar' Write-Host '' Write-Host ' Nota: re-registo aplica-se ao utilizador que elevou o toolkit.' -ForegroundColor DarkGray switch (Read-Choice) { '1' { [void](Invoke-Native 'wsreset.exe' '') Write-Ok 'Cache da Store limpa (a Store abre automaticamente no fim).' } '2' { $pkgs = Get-AppxPackage -AllUsers -Name 'Microsoft.WindowsStore' -ErrorAction SilentlyContinue if (-not $pkgs) { Write-Err 'Pacote Microsoft.WindowsStore nao encontrado.'; return } foreach ($p in $pkgs) { try { Add-AppxPackage -DisableDevelopmentMode -Register (Join-Path $p.InstallLocation 'AppXManifest.xml') -ErrorAction Stop Write-Ok "Re-registado: $($p.Name) $($p.Version)" } catch { Write-Warn "$($p.Name): $($_.Exception.Message)" } } } '3' { if (-not (Confirm-Action 'Re-registar todas as apps?')) { return } $ok = 0; $fail = 0 foreach ($p in (Get-AppxPackage -AllUsers -ErrorAction SilentlyContinue)) { $manifest = Join-Path $p.InstallLocation 'AppXManifest.xml' if (-not (Test-Path $manifest)) { continue } try { Add-AppxPackage -DisableDevelopmentMode -Register $manifest -ErrorAction Stop $ok++ } catch { $fail++; Write-Log "Appx falhou: $($p.Name) - $($_.Exception.Message)" 'WARN' } } Write-Ok "Apps re-registadas: $ok | Falhas (normais em apps em uso): $fail" } } } function Invoke-FullRepair { Write-Section 'Reparacao completa recomendada' Write-Info 'Sequencia: Ponto de restauro > CHKDSK online > DISM RestoreHealth > SFC' Write-Info 'Duracao estimada: 20-60 minutos.' if (-not (Confirm-Action 'Iniciar reparacao completa?')) { return } $t0 = Get-Date $rp = New-PSCRestorePoint 'PSC Toolkit - antes de reparacao completa' Write-Section 'Passo 1/3 - CHKDSK online' $chk = Invoke-Native 'chkdsk.exe' "$env:SystemDrive /scan" Write-Section 'Passo 2/3 - DISM RestoreHealth' $dism = Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /RestoreHealth' Write-Section 'Passo 3/3 - SFC /scannow' $sfc = Invoke-SFC $dur = New-TimeSpan -Start $t0 -End (Get-Date) Write-Section 'Resumo da reparacao' $fmt = { param($c) if ($c -eq 0) { 'OK' } else { "codigo $c" } } Write-Host (" Ponto restauro : {0}" -f $(if ($rp) { 'criado' } else { 'nao criado' })) -ForegroundColor Gray Write-Host (" CHKDSK online : {0}" -f (& $fmt $chk)) -ForegroundColor Gray Write-Host (" DISM : {0}" -f (& $fmt $dism)) -ForegroundColor Gray Write-Host (" SFC : {0}" -f (& $fmt $sfc)) -ForegroundColor Gray Write-Host (" Duracao : {0:hh\:mm\:ss}" -f $dur) -ForegroundColor Gray Write-Log ("RESUMO reparacao completa | RP={0} CHKDSK={1} DISM={2} SFC={3} | {4:hh\:mm\:ss}" -f $rp, $chk, $dism, $sfc, $dur) if ($chk -ne 0) { Write-Warn 'CHKDSK detetou problemas - agende /f no menu CHKDSK.' } if ($dism -ne 0) { Write-Warn 'DISM falhou - use a reparacao via ISO/USB.' } Write-Info 'Recomenda-se reiniciar o computador.' } function Show-RepairMenu { while ($true) { Show-Header Write-Host '' Write-Host ' REPARACAO DO SISTEMA OPERATIVO' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Reparacao completa (Restauro + CHKDSK + DISM + SFC)' -Recommended Write-Host '' Write-MenuItem '2' 'SFC /scannow' Write-MenuItem '3' 'DISM - verificar estado da imagem (ScanHealth)' Write-MenuItem '4' 'DISM - reparar imagem via Windows Update' Write-MenuItem '5' 'DISM - reparar a partir de ISO / USB' Write-MenuItem '6' 'CHKDSK - disco do sistema' Write-Host '' Write-MenuItem '7' 'Reset dos componentes do Windows Update' Write-MenuItem '8' 'Reset de rede (Winsock / TCP-IP / DNS / Proxy)' Write-MenuItem '9' 'Reparar repositorio WMI' Write-MenuItem 'A' 'Reparar Microsoft Store / Apps' Write-Host '' Write-MenuItem 'R' 'Criar ponto de restauro agora' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Invoke-FullRepair; Wait-Return } '2' { Confirm-RestorePoint; [void](Invoke-SFC); Wait-Return } '3' { [void](Invoke-DismScan); Wait-Return } '4' { Confirm-RestorePoint; [void](Invoke-DismRestore); Wait-Return } '5' { Confirm-RestorePoint; [void](Invoke-DismFromMedia); Wait-Return } '6' { Invoke-ChkdskMenu; Wait-Return } '7' { Confirm-RestorePoint; Reset-WindowsUpdate; Wait-Return } '8' { Reset-Network; Wait-Return } '9' { Confirm-RestorePoint; Repair-WMI; Wait-Return } 'A' { Repair-StoreApps; Wait-Return } 'R' { [void](New-PSCRestorePoint 'PSC Toolkit - manual'); Wait-Return } '0' { return } default { } } } } # ================================================================ # MODULO 2 - ARRANQUE E PERFORMANCE # ================================================================ function Format-Short { param([string]$Text, [int]$Max) if ($null -eq $Text) { return '' } if ($Text.Length -le $Max) { return $Text } return $Text.Substring(0, $Max - 3) + '...' } function Write-KV { param([string]$Key, [string]$Value, [string]$Color = 'Gray') Write-Host (' {0,-26}: ' -f $Key) -NoNewline -ForegroundColor DarkGray Write-Host $Value -ForegroundColor $Color Write-Log "$Key = $Value" } function Set-RegDword { param([string]$Path, [string]$Name, [int]$Value) if (-not (Test-Path $Path)) { New-Item -Path $Path -Force | Out-Null } New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType DWord -Force | Out-Null } function Get-DriveMediaType { param([string]$Letter) try { $dn = (Get-Partition -DriveLetter $Letter -ErrorAction Stop).DiskNumber $pd = Get-PhysicalDisk -ErrorAction Stop | Where-Object { $_.DeviceId -eq [string]$dn } if ($pd) { return [string]$pd.MediaType } } catch { } return 'Desconhecido' } # ---------- Programas de arranque (mesmo mecanismo do Gestor de Tarefas) ---------- function Test-StartupEnabled { param([string]$ApprovedKey, [string]$Name) $v = (Get-ItemProperty -Path $ApprovedKey -Name $Name -ErrorAction SilentlyContinue).$Name if ($null -eq $v -or $v.Count -eq 0) { return $true } return (($v[0] -band 1) -eq 0) } function Get-PSCStartupItems { $ea = 'Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved' $regDefs = @( @{ Scope = 'Maquina'; Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Approved = "HKLM:\$ea\Run" }, @{ Scope = 'Maquina32'; Path = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; Approved = "HKLM:\$ea\Run32" }, @{ Scope = 'Utilizador'; Path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'; Approved = "HKCU:\$ea\Run" } ) $items = @() foreach ($d in $regDefs) { if (-not (Test-Path $d.Path)) { continue } $key = Get-Item -Path $d.Path foreach ($n in $key.GetValueNames()) { if ([string]::IsNullOrEmpty($n)) { continue } $items += [pscustomobject]@{ Name = $n; Command = [string]$key.GetValue($n); Scope = $d.Scope Approved = $d.Approved; Enabled = (Test-StartupEnabled $d.Approved $n) } } } $folderDefs = @( @{ Scope = 'Pasta-User'; Path = (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup'); Approved = "HKCU:\$ea\StartupFolder" }, @{ Scope = 'Pasta-Todos'; Path = (Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\StartUp'); Approved = "HKLM:\$ea\StartupFolder" } ) foreach ($d in $folderDefs) { foreach ($f in (Get-ChildItem -Path $d.Path -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -ne 'desktop.ini' })) { $items += [pscustomobject]@{ Name = $f.Name; Command = $f.FullName; Scope = $d.Scope Approved = $d.Approved; Enabled = (Test-StartupEnabled $d.Approved $f.Name) } } } return $items } function Set-StartupItemState { param($Item, [bool]$Enable) if (-not (Test-Path $Item.Approved)) { New-Item -Path $Item.Approved -Force | Out-Null } $bytes = New-Object byte[] 12 if ($Enable) { $bytes[0] = 2 } else { $bytes[0] = 3 [Array]::Copy([BitConverter]::GetBytes((Get-Date).ToFileTime()), 0, $bytes, 4, 8) } Set-ItemProperty -Path $Item.Approved -Name $Item.Name -Value $bytes -Type Binary $state = if ($Enable) { 'ATIVADO' } else { 'DESATIVADO' } Write-Ok "Arranque $state : $($Item.Name) ($($Item.Scope))" } function Show-StartupManager { while ($true) { Show-Header Write-Host '' Write-Host ' PROGRAMAS DE ARRANQUE' -ForegroundColor DarkYellow Write-Host ' (reversivel - igual ao separador Arranque do Gestor de Tarefas)' -ForegroundColor DarkGray Write-Host '' $items = @(Get-PSCStartupItems) if ($items.Count -eq 0) { Write-Info 'Nenhum programa de arranque encontrado.'; Wait-Return; return } for ($i = 0; $i -lt $items.Count; $i++) { $it = $items[$i] $state = if ($it.Enabled) { 'ON ' } else { 'OFF' } $color = if ($it.Enabled) { 'Green' } else { 'DarkGray' } Write-Host (' [{0,2}] ' -f ($i + 1)) -NoNewline -ForegroundColor DarkYellow Write-Host "[$state] " -NoNewline -ForegroundColor $color Write-Host ('{0,-30} {1,-11}' -f (Format-Short $it.Name 30), $it.Scope) -NoNewline -ForegroundColor White Write-Host (Format-Short $it.Command 45) -ForegroundColor DarkGray } Write-Host '' Write-Host ' Nota: entradas "Utilizador" referem-se a conta que elevou o toolkit.' -ForegroundColor DarkGray $sel = Read-Choice 'Numero para ativar/desativar (0 = voltar)' if ($sel -eq '0' -or $sel -eq '') { return } if ($sel -match '^\d+$' -and [int]$sel -ge 1 -and [int]$sel -le $items.Count) { $it = $items[[int]$sel - 1] try { Set-StartupItemState -Item $it -Enable (-not $it.Enabled) } catch { Write-Err "Falha ao alterar $($it.Name): $($_.Exception.Message)" } Start-Sleep -Milliseconds 700 } } } # ---------- Servicos de terceiros ---------- function Get-ServiceExePath { param([string]$PathName) if ([string]::IsNullOrWhiteSpace($PathName)) { return $null } if ($PathName -match '^\s*"([^"]+)"') { return $Matches[1] } if ($PathName -match '^\s*(.+?\.exe)') { return $Matches[1] } return $null } function Get-PSCThirdPartyServices { $result = @() $svcs = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.StartMode -in 'Auto', 'Manual' } foreach ($s in $svcs) { $exe = Get-ServiceExePath $s.PathName if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { continue } $company = (Get-Item -LiteralPath $exe -ErrorAction SilentlyContinue).VersionInfo.CompanyName if ($company -match 'Microsoft') { continue } $result += [pscustomobject]@{ Name = $s.Name; Display = $s.DisplayName; Mode = $s.StartMode State = $s.State; Company = [string]$company } } return ($result | Sort-Object Mode, Display) } $script:CriticalServicePattern = 'antivir|defender|eset|kaspersky|bitdefender|avast|avg|norton|sophos|malwarebytes|trend ?micro|panda|mcafee|sentinel|crowdstrike|webroot|veeam|msp360|cloudberry|backup|anydesk|teamviewer|rustdesk|splashtop|vpn|fortinet|forti|cisco' function Show-ServicesManager { Write-Info 'A analisar servicos de terceiros (pode demorar alguns segundos)...' $svcs = @(Get-PSCThirdPartyServices) while ($true) { Show-Header Write-Host '' Write-Host ' SERVICOS DE TERCEIROS (nao-Microsoft)' -ForegroundColor DarkYellow Write-Host ' Alterna entre Automatico <-> Manual. Manual = so arranca quando necessario.' -ForegroundColor DarkGray Write-Host '' if ($svcs.Count -eq 0) { Write-Info 'Nenhum servico de terceiros encontrado.'; Wait-Return; return } for ($i = 0; $i -lt $svcs.Count; $i++) { $s = $svcs[$i] $critical = ($s.Display + ' ' + $s.Company + ' ' + $s.Name) -match $script:CriticalServicePattern $modeColor = if ($s.Mode -eq 'Auto') { 'Green' } else { 'DarkGray' } Write-Host (' [{0,2}] ' -f ($i + 1)) -NoNewline -ForegroundColor DarkYellow Write-Host ('{0,-7}' -f $s.Mode) -NoNewline -ForegroundColor $modeColor Write-Host ('{0,-40} ' -f (Format-Short $s.Display 40)) -NoNewline -ForegroundColor White Write-Host (Format-Short $s.Company 25) -NoNewline -ForegroundColor DarkGray if ($critical) { Write-Host ' [CRITICO]' -ForegroundColor Red } else { Write-Host '' } } Write-Host '' Write-Host ' [CRITICO] = seguranca / backup / acesso remoto / VPN - nao alterar sem certeza.' -ForegroundColor DarkGray $sel = Read-Choice 'Numero para alternar (0 = voltar)' if ($sel -eq '0' -or $sel -eq '') { return } if ($sel -match '^\d+$' -and [int]$sel -ge 1 -and [int]$sel -le $svcs.Count) { $s = $svcs[[int]$sel - 1] if (($s.Display + ' ' + $s.Company + ' ' + $s.Name) -match $script:CriticalServicePattern) { if (-not (Confirm-Action "ATENCAO: '$($s.Display)' parece critico. Alterar mesmo assim?")) { continue } } $newMode = if ($s.Mode -eq 'Auto') { 'Manual' } else { 'Automatic' } try { Set-Service -Name $s.Name -StartupType $newMode -ErrorAction Stop $s.Mode = if ($newMode -eq 'Automatic') { 'Auto' } else { 'Manual' } Write-Ok "Servico $($s.Name) -> $newMode" } catch { Write-Err "Falha em $($s.Name): $($_.Exception.Message)" } Start-Sleep -Milliseconds 700 } } } # ---------- Energia, Hibernacao, Arranque Rapido ---------- $script:FastStartupKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power' function Get-FastStartup { return ((Get-ItemProperty -Path $script:FastStartupKey -Name HiberbootEnabled -ErrorAction SilentlyContinue).HiberbootEnabled -eq 1) } function Set-FastStartup { param([bool]$Enable) Set-RegDword $script:FastStartupKey 'HiberbootEnabled' ([int]$Enable) $state = if ($Enable) { 'ATIVADO' } else { 'DESATIVADO' } Write-Ok "Arranque Rapido $state." } function Get-Hibernation { return ((Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Power' -Name HibernateEnabled -ErrorAction SilentlyContinue).HibernateEnabled -eq 1) } function Get-PSCPowerPlans { $plans = @() # powercfg escreve na code page OEM (ex: 850) - descodificar corretamente os acentos $prevEnc = [Console]::OutputEncoding try { [Console]::OutputEncoding = [Text.Encoding]::GetEncoding([Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage) $lines = & powercfg.exe /list } finally { [Console]::OutputEncoding = $prevEnc } foreach ($l in $lines) { if ($l -match '([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\s+\((.+)\)(\s*\*)?') { $plans += [pscustomobject]@{ Guid = $Matches[1]; Name = $Matches[2]; Active = [bool]$Matches[3] } } } return $plans } function Disable-PSCPCIeASPM { Write-Section 'Fix Estabilidade NVMe / BSOD 0x124 (Desativar PCIe ASPM)' Write-Info 'Impede que o barramento PCI Express adormeca o SSD NVMe e cause ecras WHEA 0x124 (0%).' [void](Invoke-Native 'powercfg.exe' '/setacvalueindex SCHEME_CURRENT SUB_PCIEXPRESS ASPM 0') [void](Invoke-Native 'powercfg.exe' '/setdcvalueindex SCHEME_CURRENT SUB_PCIEXPRESS ASPM 0') [void](Invoke-Native 'powercfg.exe' '/setactive SCHEME_CURRENT') Write-Ok 'Poupanca de energia PCI Express (ASPM) desativada em Corrente e Bateria.' } function Show-PowerMenu { while ($true) { Show-Header Write-Host '' Write-Host ' ENERGIA, HIBERNACAO E ARRANQUE RAPIDO' -ForegroundColor DarkYellow Write-Host '' $plans = @(Get-PSCPowerPlans) for ($i = 0; $i -lt $plans.Count; $i++) { $p = $plans[$i] $mark = if ($p.Active) { ' <- ATIVO' } else { '' } Write-Host (' [{0}] ' -f ($i + 1)) -NoNewline -ForegroundColor DarkYellow Write-Host $p.Name -NoNewline -ForegroundColor White Write-Host $mark -ForegroundColor Green } $hib = Get-Hibernation $fs = Get-FastStartup Write-Host '' Write-MenuItem 'U' 'Criar e ativar plano "Desempenho Maximo" (desktops de bancada)' Write-MenuItem 'H' ("Hibernacao: {0} -> alternar" -f $(if ($hib) { 'ATIVA' } else { 'INATIVA' })) Write-MenuItem 'F' ("Arranque Rapido: {0} -> alternar" -f $(if ($fs -and $hib) { 'ATIVO' } elseif ($fs) { 'ATIVO (sem efeito: hibernacao off)' } else { 'INATIVO' })) Write-MenuItem 'P' 'Fix BSOD NVMe (0x124 WHEA): Desativar Poupanca Energia PCIe (ASPM)' -Recommended Write-MenuItem '0' 'Voltar' Write-Host '' Write-Host ' Dica: Arranque Rapido OFF evita "uptime" infinito, falhas de updates e drivers.' -ForegroundColor DarkGray Write-Host ' Em portateis mantenha o plano Equilibrado (bateria/temperatura).' -ForegroundColor DarkGray $sel = Read-Choice switch -Regex ($sel) { '^0$' { return } '^\d+$' { $n = [int]$sel if ($n -ge 1 -and $n -le $plans.Count) { [void](Invoke-Native 'powercfg.exe' "/setactive $($plans[$n - 1].Guid)") Write-Ok "Plano ativo: $($plans[$n - 1].Name)" Start-Sleep -Milliseconds 800 } } '^U$' { $out = & powercfg.exe -duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 2>&1 if ("$out" -match '([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})') { [void](Invoke-Native 'powercfg.exe' "/setactive $($Matches[1])") Write-Ok 'Plano Desempenho Maximo criado e ativado.' } else { Write-Warn "Nao foi possivel criar o plano: $out" } Wait-Return } '^H$' { if ($hib) { Write-Warn 'Desativar hibernacao liberta o hiberfil.sys mas desativa tambem o Arranque Rapido.' if (Confirm-Action 'Desativar hibernacao?') { [void](Invoke-Native 'powercfg.exe' '/hibernate off'); Write-Ok 'Hibernacao desativada.' } } else { [void](Invoke-Native 'powercfg.exe' '/hibernate on'); Write-Ok 'Hibernacao ativada.' } Start-Sleep -Milliseconds 800 } '^F$' { Set-FastStartup (-not $fs); Start-Sleep -Milliseconds 800 } '^P$' { Disable-PSCPCIeASPM; Wait-Return } } } } # ---------- Discos ---------- function Invoke-OptimizeDrives { Write-Section 'Otimizar discos (TRIM em SSD / Desfragmentar em HDD)' Write-Info 'O Windows escolhe automaticamente a operacao correta para cada tipo de disco.' $vols = Get-Volume -ErrorAction SilentlyContinue | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter -and $_.FileSystem -eq 'NTFS' } foreach ($v in $vols) { $letter = [string]$v.DriveLetter $type = Get-DriveMediaType $letter Write-Info "Unidade ${letter}: ($type) - a otimizar..." try { Optimize-Volume -DriveLetter $letter -Verbose -ErrorAction Stop Write-Ok "Unidade ${letter}: otimizada." } catch { Write-Warn "Unidade ${letter}: $($_.Exception.Message)" } } } # ---------- Bloatware ---------- $script:BloatList = @( @{ P = 'Microsoft.BingNews'; D = 'Noticias (Bing News)' }, @{ P = 'Microsoft.BingWeather'; D = 'Meteorologia' }, @{ P = 'Microsoft.BingFinance'; D = 'Financas' }, @{ P = 'Microsoft.BingSports'; D = 'Desporto' }, @{ P = 'Microsoft.GetHelp'; D = 'Obter Ajuda' }, @{ P = 'Microsoft.Getstarted'; D = 'Sugestoes / Introducao' }, @{ P = 'Microsoft.MicrosoftSolitaireCollection'; D = 'Solitaire Collection' }, @{ P = 'Microsoft.People'; D = 'Pessoas' }, @{ P = 'Microsoft.WindowsFeedbackHub'; D = 'Hub de Comentarios' }, @{ P = 'Microsoft.WindowsMaps'; D = 'Mapas' }, @{ P = 'Microsoft.MicrosoftOfficeHub'; D = 'Microsoft 365 (Office Hub)' }, @{ P = 'Microsoft.SkypeApp'; D = 'Skype' }, @{ P = 'Microsoft.Todos'; D = 'Microsoft To Do' }, @{ P = 'Clipchamp.Clipchamp'; D = 'Clipchamp' }, @{ P = 'MicrosoftTeams'; D = 'Teams (pessoal)' }, @{ P = 'Microsoft.549981C3F5F10'; D = 'Cortana' }, @{ P = 'Microsoft.ZuneVideo'; D = 'Filmes e TV' }, @{ P = 'Microsoft.MixedReality.Portal'; D = 'Mixed Reality Portal' }, @{ P = 'Microsoft.Microsoft3DViewer'; D = 'Visualizador 3D' }, @{ P = 'Microsoft.PowerAutomateDesktop'; D = 'Power Automate' }, @{ P = '*CandyCrush*'; D = 'Candy Crush' }, @{ P = 'king.com.*'; D = 'Jogos King' } ) function Show-BloatwareMenu { Write-Section 'Remover bloatware (apps pre-instaladas)' Write-Info 'A procurar apps instaladas...' $found = @() foreach ($b in $script:BloatList) { $pk = @(Get-AppxPackage -AllUsers -Name $b.P -ErrorAction SilentlyContinue) if ($pk.Count -gt 0) { $found += [pscustomobject]@{ Pattern = $b.P; Desc = $b.D; Pkgs = $pk } } } if ($found.Count -eq 0) { Write-Ok 'Nenhuma app da lista PSC encontrada. Sistema limpo.'; return } for ($i = 0; $i -lt $found.Count; $i++) { Write-MenuItem ($i + 1) ('{0,-28} {1}' -f $found[$i].Desc, $found[$i].Pattern) } $sel = Read-Choice 'Numeros separados por virgula, T = todos, 0 = voltar' if ($sel -eq '0' -or $sel -eq '') { return } $targets = @() if ($sel -eq 'T') { $targets = $found } else { foreach ($n in ($sel -split '[,; ]+')) { if ($n -match '^\d+$' -and [int]$n -ge 1 -and [int]$n -le $found.Count) { $targets += $found[[int]$n - 1] } } } if ($targets.Count -eq 0) { Write-Warn 'Nenhuma selecao valida.'; return } Write-Host '' $targets | ForEach-Object { Write-Host " - $($_.Desc)" -ForegroundColor Gray } if (-not (Confirm-Action "Remover $($targets.Count) app(s) para todos os utilizadores?")) { return } $prov = Confirm-Action 'Remover tambem da imagem (nao reinstala em novos utilizadores)?' foreach ($t in $targets) { foreach ($p in $t.Pkgs) { try { Remove-AppxPackage -Package $p.PackageFullName -AllUsers -ErrorAction Stop Write-Ok "Removido: $($p.Name)" } catch { Write-Warn "$($p.Name): $($_.Exception.Message)" } } if ($prov) { Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like $t.Pattern } | ForEach-Object { try { Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction Stop | Out-Null Write-Ok "Removido da imagem: $($_.DisplayName)" } catch { Write-Warn "Imagem $($_.DisplayName): $($_.Exception.Message)" } } } } } # ---------- Privacidade e Animacoes ---------- function Set-PSCPrivacy { param([bool]$Harden) $v = if ($Harden) { 0 } else { 1 } $cdm = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager' foreach ($n in 'SilentInstalledAppsEnabled', 'SystemPaneSuggestionsEnabled', 'SoftLandingEnabled', 'SubscribedContent-338388Enabled', 'SubscribedContent-338389Enabled', 'SubscribedContent-353694Enabled', 'SubscribedContent-353696Enabled') { Set-RegDword $cdm $n $v } Set-RegDword 'HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo' 'Enabled' $v $dc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection' try { if ($Harden) { Set-RegDword $dc 'AllowTelemetry' 1 # 1 = minimo permitido em Home/Pro Stop-Service -Name DiagTrack -Force -ErrorAction SilentlyContinue Set-Service -Name DiagTrack -StartupType Disabled -ErrorAction Stop Write-Ok 'Sugestoes, apps silenciosas, ID de publicidade e telemetria reduzidos.' } else { Remove-ItemProperty -Path $dc -Name 'AllowTelemetry' -ErrorAction SilentlyContinue Set-Service -Name DiagTrack -StartupType Automatic -ErrorAction Stop Start-Service -Name DiagTrack -ErrorAction SilentlyContinue Write-Ok 'Definicoes de privacidade repostas para as predefinicoes do Windows.' } } catch { Write-Warn "DiagTrack: $($_.Exception.Message)" } } function Set-PSCAnimations { param([bool]$Reduce) $desk = 'HKCU:\Control Panel\Desktop' $adv = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' $pers = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' if ($Reduce) { Set-ItemProperty -Path "$desk\WindowMetrics" -Name MinAnimate -Value '0' Set-ItemProperty -Path $desk -Name MenuShowDelay -Value '100' Set-RegDword $adv 'TaskbarAnimations' 0 Set-RegDword $pers 'EnableTransparency' 0 Write-Ok 'Animacoes e transparencias reduzidas (fontes e miniaturas mantidas).' } else { Set-ItemProperty -Path "$desk\WindowMetrics" -Name MinAnimate -Value '1' Set-ItemProperty -Path $desk -Name MenuShowDelay -Value '400' Set-RegDword $adv 'TaskbarAnimations' 1 Set-RegDword $pers 'EnableTransparency' 1 Write-Ok 'Animacoes e transparencias repostas.' } Write-Info 'Efeito completo apos terminar sessao. Aplica-se a conta que elevou o toolkit.' } function Show-ToggleMenu { param([string]$Title, [scriptblock]$Action) Write-Section $Title Write-MenuItem '1' 'Aplicar otimizacao' -Recommended Write-MenuItem '2' 'Repor predefinicoes do Windows' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { & $Action $true } '2' { & $Action $false } } } # ---------- Analise ---------- function Show-BootAnalysis { Write-Section 'Analise de arranque e desempenho' Write-Log '--- ANALISE DE ARRANQUE ---' $os = Get-CimInstance Win32_OperatingSystem $up = (Get-Date) - $os.LastBootUpTime $ramTotal = $os.TotalVisibleMemorySize / 1MB $ramUsed = ($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / 1MB $ramPct = [math]::Round(($ramUsed / $ramTotal) * 100) $fs = Get-FastStartup $hib = Get-Hibernation $sysType = Get-DriveMediaType $env:SystemDrive.Substring(0, 1) Write-KV 'Ultimo arranque' ('{0:dd-MM-yyyy HH:mm} ({1:N1} dias)' -f $os.LastBootUpTime, $up.TotalDays) $(if ($up.TotalDays -gt 7) { 'Yellow' } else { 'Gray' }) Write-KV 'Arranque Rapido' $(if ($fs -and $hib) { 'ATIVO' } else { 'INATIVO' }) Write-KV 'Disco do sistema' $sysType $(if ($sysType -eq 'HDD') { 'Yellow' } else { 'Gray' }) Write-KV 'Memoria RAM' ('{0:N1} / {1:N1} GB ({2}%)' -f $ramUsed, $ramTotal, $ramPct) $(if ($ramPct -gt 85) { 'Yellow' } else { 'Gray' }) $active = Get-PSCPowerPlans | Where-Object Active Write-KV 'Plano de energia' $(if ($active) { $active.Name } else { 'n/d' }) # Tempos de arranque (Diagnostics-Performance, evento 100) $ev = Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Diagnostics-Performance/Operational'; Id = 100 } -MaxEvents 5 -ErrorAction SilentlyContinue if ($ev) { $times = foreach ($e in $ev) { $x = [xml]$e.ToXml() $bt = ($x.Event.EventData.Data | Where-Object { $_.Name -eq 'BootTime' }).'#text' if ($bt) { [math]::Round([int]$bt / 1000, 1) } } $avg = [math]::Round(($times | Measure-Object -Average).Average, 1) Write-KV 'Tempo arranque (ult. 5)' ("{0} s | media {1} s" -f ($times -join ' / '), $avg) $(if ($avg -gt 60) { 'Yellow' } else { 'Gray' }) } else { Write-KV 'Tempo arranque' 'sem registos de diagnostico' 'DarkGray' } $si = @(Get-PSCStartupItems) $siOn = @($si | Where-Object Enabled).Count Write-KV 'Programas de arranque' ("{0} ativos / {1} total" -f $siOn, $si.Count) $(if ($siOn -gt 10) { 'Yellow' } else { 'Gray' }) $tasks = @(Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object { $_.TaskPath -notlike '\Microsoft\*' -and $_.State -ne 'Disabled' -and ($_.Triggers | Where-Object { $_.CimClass.CimClassName -in 'MSFT_TaskLogonTrigger', 'MSFT_TaskBootTrigger' }) }) Write-KV 'Tarefas no logon/arranque' ("{0} (terceiros)" -f $tasks.Count) foreach ($t in ($tasks | Select-Object -First 8)) { Write-Host " - $($t.TaskName)" -ForegroundColor DarkGray } $svcAuto = @(Get-PSCThirdPartyServices | Where-Object { $_.Mode -eq 'Auto' }) Write-KV 'Servicos terceiros (Auto)' $svcAuto.Count $(if ($svcAuto.Count -gt 15) { 'Yellow' } else { 'Gray' }) Write-Host '' Write-Host ' RECOMENDACOES' -ForegroundColor DarkYellow $rec = 0 if ($up.TotalDays -gt 7) { if ($fs -and $hib) { Write-Warn 'Uptime elevado com Arranque Rapido ativo - desativar (menu Energia) e reiniciar.' } else { Write-Warn ('Sem reiniciar ha {0:N0} dias - reiniciar antes de diagnosticar.' -f $up.TotalDays) } $rec++ } if ($sysType -eq 'HDD') { Write-Warn 'Disco de sistema HDD - recomendar upgrade para SSD ao cliente.'; $rec++ } if ($ramPct -gt 85) { Write-Warn "RAM a $ramPct% - considerar upgrade de memoria."; $rec++ } if ($siOn -gt 10) { Write-Warn "$siOn programas no arranque - rever no menu Programas de arranque."; $rec++ } if ($rec -eq 0) { Write-Ok 'Sem alertas relevantes.' } } function Invoke-RecommendedOptimization { Write-Section 'Otimizacao recomendada' Write-Info 'Sequencia: Ponto de restauro > Otimizar discos > Privacidade/sugestoes > Arranque Rapido > Analise' Write-Info 'Nao desativa programas nem servicos automaticamente (revisao manual nas opcoes 3 e 4).' if (-not (Confirm-Action 'Iniciar otimizacao recomendada?')) { return } [void](New-PSCRestorePoint 'PSC Toolkit - antes de otimizacao') Invoke-OptimizeDrives Write-Section 'Privacidade, sugestoes e telemetria' Set-PSCPrivacy $true if (Get-FastStartup) { Write-Section 'Arranque Rapido' if (Confirm-Action 'Desativar Arranque Rapido? (recomendado: evita falhas de updates/drivers)') { Set-FastStartup $false } } Show-BootAnalysis Write-Info 'Reveja agora os programas de arranque (opcao 3) e servicos de terceiros (opcao 4).' } function Show-PerformanceMenu { while ($true) { Show-Header Write-Host '' Write-Host ' ARRANQUE E PERFORMANCE' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Otimizacao recomendada (Restauro + Discos + Privacidade + Analise)' -Recommended Write-MenuItem '2' 'Analise de arranque e desempenho (so leitura)' Write-Host '' Write-MenuItem '3' 'Gerir programas de arranque' Write-MenuItem '4' 'Servicos de terceiros (Automatico / Manual)' Write-MenuItem '5' 'Plano de energia, Hibernacao e Arranque Rapido' Write-MenuItem '6' 'Otimizar discos (TRIM SSD / Desfragmentar HDD)' Write-Host '' Write-MenuItem '7' 'Remover bloatware (apps pre-instaladas)' Write-MenuItem '8' 'Privacidade: sugestoes, anuncios e telemetria' Write-MenuItem '9' 'Reduzir animacoes e transparencias' Write-Host '' Write-MenuItem 'R' 'Criar ponto de restauro agora' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Invoke-RecommendedOptimization; Wait-Return } '2' { Show-BootAnalysis; Wait-Return } '3' { Show-StartupManager } '4' { Show-ServicesManager } '5' { Show-PowerMenu } '6' { Invoke-OptimizeDrives; Wait-Return } '7' { Confirm-RestorePoint; Show-BloatwareMenu; Wait-Return } '8' { Show-ToggleMenu 'Privacidade: sugestoes, anuncios e telemetria' { param($a) Set-PSCPrivacy $a }; Wait-Return } '9' { Show-ToggleMenu 'Animacoes e transparencias' { param($a) Set-PSCAnimations $a }; Wait-Return } 'R' { [void](New-PSCRestorePoint 'PSC Toolkit - manual'); Wait-Return } '0' { return } default { } } } } # ================================================================ # MODULO 3 - LIMPEZA PROFUNDA # ================================================================ function Format-Bytes { param([double]$Bytes) if ($Bytes -ge 1GB) { return '{0:N2} GB' -f ($Bytes / 1GB) } if ($Bytes -ge 1MB) { return '{0:N1} MB' -f ($Bytes / 1MB) } if ($Bytes -ge 1KB) { return '{0:N0} KB' -f ($Bytes / 1KB) } return ('{0:N0} B' -f $Bytes) } function Get-SystemFreeBytes { return [double](Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'" -ErrorAction SilentlyContinue).FreeSpace } function Get-PSCProfiles { if (-not $script:PSCProfilesCache) { $script:PSCProfilesCache = @(Get-CimInstance Win32_UserProfile -ErrorAction SilentlyContinue | Where-Object { -not $_.Special -and $_.LocalPath -and (Test-Path -LiteralPath $_.LocalPath) } | ForEach-Object { $_.LocalPath }) } return $script:PSCProfilesCache } function Get-PSCFilesSafe { <# Enumera ficheiros sem seguir junctions/symlinks (evita apagar fora da pasta alvo). Opcionalmente filtra por idade minima e por regex do nome, e recolhe subpastas em $DirList. #> param( [string]$Root, [int]$MinAgeDays = 0, [string]$NameMatch = '', [System.Collections.Generic.List[string]]$DirList = $null ) $limit = (Get-Date).AddDays(-$MinAgeDays) if ([IO.File]::Exists($Root)) { $fi = New-Object IO.FileInfo $Root if (($MinAgeDays -le 0 -or $fi.LastWriteTime -le $limit) -and (-not $NameMatch -or $fi.Name -match $NameMatch)) { $fi } return } if (-not [IO.Directory]::Exists($Root)) { return } $stack = New-Object System.Collections.Generic.Stack[string] $stack.Push($Root) while ($stack.Count -gt 0) { $di = New-Object IO.DirectoryInfo ($stack.Pop()) try { $files = $di.GetFiles() } catch { $files = @() } foreach ($f in $files) { if ($MinAgeDays -gt 0 -and $f.LastWriteTime -gt $limit) { continue } if ($NameMatch -and $f.Name -notmatch $NameMatch) { continue } $f } try { $subs = $di.GetDirectories() } catch { $subs = @() } foreach ($s in $subs) { if ($s.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue } if ($null -ne $DirList) { $DirList.Add($s.FullName) } $stack.Push($s.FullName) } } } function Get-PSCCleanCategories { # Caches dos browsers - APENAS cache (nunca cookies, historico, passwords ou sessoes) $browserPaths = @() foreach ($c in 'Google\Chrome\User Data', 'Microsoft\Edge\User Data', 'BraveSoftware\Brave-Browser\User Data', 'Vivaldi\User Data') { foreach ($sub in 'Cache', 'Code Cache', 'GPUCache') { $browserPaths += "{P}\AppData\Local\$c\*\$sub" } } $browserPaths += '{P}\AppData\Local\Opera Software\*\Cache' $browserPaths += '{P}\AppData\Local\Mozilla\Firefox\Profiles\*\cache2' $wer = Join-Path $env:ProgramData 'Microsoft\Windows\WER' $recycle = @(Get-Volume -ErrorAction SilentlyContinue | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter } | ForEach-Object { '{0}:\$Recycle.Bin' -f $_.DriveLetter }) $def = { param($Id, $Name, $Paths, $Age, $Match, $Rec, $Pre, $Dirs) [pscustomobject]@{ Id = $Id; Name = $Name; Paths = $Paths; Age = $Age; Match = $Match; Rec = $Rec; Pre = $Pre; Dirs = $Dirs } } @( (& $def 'TEMP' 'Temporarios dos utilizadores' @('{P}\AppData\Local\Temp') 1 '' $true '' $true), (& $def 'WTEMP' 'Temporarios do Windows' @("$env:windir\Temp") 1 '' $true '' $true), (& $def 'WU' 'Cache do Windows Update' @("$env:windir\SoftwareDistribution\Download") 0 '' $true 'WU' $true), (& $def 'DO' 'Cache de Otimizacao de Entrega' @("$env:windir\ServiceProfiles\NetworkService\AppData\Local\Microsoft\Windows\DeliveryOptimization\Cache") 0 '' $true 'DO' $true), (& $def 'BROWSER' 'Cache dos browsers (sem cookies)' $browserPaths 0 '' $true 'BROWSER' $false), (& $def 'WER' 'Relatorios de erros (WER)' @("$wer\ReportArchive", "$wer\ReportQueue", "$wer\Temp", '{P}\AppData\Local\Microsoft\Windows\WER') 0 '' $true '' $true), (& $def 'LOGS' 'Logs antigos do sistema (> 14 dias)' @("$env:windir\Logs") 14 '' $true '' $false), (& $def 'THUMB' 'Cache de miniaturas e icones' @('{P}\AppData\Local\Microsoft\Windows\Explorer') 0 '^(thumbcache|iconcache)_.*\.db$' $true '' $false), (& $def 'DUMP' 'Dumps de memoria (manter se ha BSOD)' @("$env:windir\Minidump", "$env:windir\MEMORY.DMP", '{P}\AppData\Local\CrashDumps') 0 '' $false '' $false), (& $def 'PREFETCH' 'Prefetch (1o arranque fica mais lento)' @("$env:windir\Prefetch") 0 '\.pf$' $false '' $false), (& $def 'RECYCLE' 'Reciclagem (todos os discos)' $recycle 0 '' $false 'RECYCLE' $false) ) } function Resolve-PSCCategoryRoots { param($Cat) $profiles = @(Get-PSCProfiles) foreach ($pat in $Cat.Paths) { $list = if ($pat.StartsWith('{P}')) { $profiles | ForEach-Object { $pat.Replace('{P}', $_) } } else { @($pat) } foreach ($p in $list) { if ($p.Contains('*')) { Get-Item -Path $p -Force -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } } elseif (Test-Path -LiteralPath $p -ErrorAction SilentlyContinue) { $p } } } } function Measure-PSCCategory { param($Cat) $bytes = 0.0; $count = 0 foreach ($r in (Resolve-PSCCategoryRoots $Cat)) { foreach ($f in (Get-PSCFilesSafe -Root $r -MinAgeDays $Cat.Age -NameMatch $Cat.Match)) { $bytes += $f.Length; $count++ } } [pscustomobject]@{ Cat = $Cat; Bytes = $bytes; Files = $count } } function Stop-PSCBrowsers { $running = @(Get-Process -Name 'chrome', 'msedge', 'firefox', 'brave', 'opera', 'vivaldi' -ErrorAction SilentlyContinue) if ($running.Count -eq 0) { return } $list = ($running | Select-Object -ExpandProperty ProcessName -Unique) -join ', ' Write-Warn "Browsers abertos: $list" if (Confirm-Action 'Fechar os browsers agora? (separadores abertos serao fechados)') { $running | Stop-Process -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 } else { Write-Info 'Ficheiros em uso serao ignorados.' } } function Clear-PSCCategory { param($Cat) Write-Info "A limpar: $($Cat.Name)" switch ($Cat.Pre) { 'WU' { foreach ($s in 'wuauserv', 'bits', 'usosvc') { Stop-Service -Name $s -Force -ErrorAction SilentlyContinue } } 'DO' { if (Get-Command Delete-DeliveryOptimizationCache -ErrorAction SilentlyContinue) { try { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop | Out-Null } catch { } } } 'BROWSER' { Stop-PSCBrowsers } 'RECYCLE' { $m = Measure-PSCCategory $Cat try { Clear-RecycleBin -Force -ErrorAction Stop Write-Ok ("Reciclagem esvaziada: {0}" -f (Format-Bytes $m.Bytes)) } catch { Write-Warn "Reciclagem: $($_.Exception.Message)" } return $m.Bytes } } $freed = 0.0; $deleted = 0; $locked = 0 foreach ($r in (Resolve-PSCCategoryRoots $Cat)) { $dirs = New-Object System.Collections.Generic.List[string] foreach ($f in (Get-PSCFilesSafe -Root $r -MinAgeDays $Cat.Age -NameMatch $Cat.Match -DirList $dirs)) { try { $len = $f.Length if ($f.IsReadOnly) { $f.IsReadOnly = $false } $f.Delete() $freed += $len; $deleted++ } catch { $locked++ } } if ($Cat.Dirs) { for ($i = $dirs.Count - 1; $i -ge 0; $i--) { try { [IO.Directory]::Delete($dirs[$i], $false) } catch { } } } } if ($Cat.Pre -eq 'WU') { foreach ($s in 'bits', 'wuauserv') { Start-Service -Name $s -ErrorAction SilentlyContinue } } $msg = '{0}: {1} libertados ({2} ficheiros)' -f $Cat.Name, (Format-Bytes $freed), $deleted if ($locked -gt 0) { $msg += " | $locked em uso, ignorados" } Write-Ok $msg return $freed } function Show-CleanAnalysis { Write-Section 'Analise de espaco recuperavel' Write-Info 'A analisar categorias (pode demorar 1-2 minutos)...' Write-Host '' Write-Log '--- ANALISE DE LIMPEZA ---' $results = @() $cats = @(Get-PSCCleanCategories) for ($i = 0; $i -lt $cats.Count; $i++) { $m = Measure-PSCCategory $cats[$i] $results += $m $color = if ($m.Bytes -ge 1GB) { 'Yellow' } elseif ($m.Bytes -gt 0) { 'White' } else { 'DarkGray' } Write-Host (' [{0,2}] ' -f ($i + 1)) -NoNewline -ForegroundColor DarkYellow Write-Host ('{0,-40}' -f $m.Cat.Name) -NoNewline -ForegroundColor $color Write-Host ('{0,12}' -f (Format-Bytes $m.Bytes)) -NoNewline -ForegroundColor $color Write-Host ('{0,10} fich.' -f $m.Files) -NoNewline -ForegroundColor DarkGray if ($m.Cat.Rec) { Write-Host ' *' -ForegroundColor Green } else { Write-Host '' } Write-Log ('{0} = {1} ({2} ficheiros)' -f $m.Cat.Name, (Format-Bytes $m.Bytes), $m.Files) } $total = ($results | Measure-Object -Property Bytes -Sum).Sum $recTotal = ($results | Where-Object { $_.Cat.Rec } | Measure-Object -Property Bytes -Sum).Sum Write-Host '' Write-KV 'Total recuperavel' (Format-Bytes $total) 'White' Write-KV 'Recomendado (*)' (Format-Bytes $recTotal) 'Green' Write-Host ' Nao inclui WinSxS / Windows.old (opcoes 4 e 5).' -ForegroundColor DarkGray return $results } function Write-CleanSummary { param([double]$Before) $after = Get-SystemFreeBytes $script:SysInfo = Get-PSCSystemInfo Write-Section 'Resumo da limpeza' Write-KV 'Espaco livre antes' (Format-Bytes $Before) Write-KV 'Espaco livre depois' (Format-Bytes $after) Write-KV "Recuperado em $env:SystemDrive" (Format-Bytes ([math]::Max(0, $after - $Before))) 'Green' } function Invoke-ComponentCleanup { Write-Section 'Limpeza de componentes do Windows (WinSxS)' Write-MenuItem '1' 'Analisar repositorio de componentes (so leitura)' Write-MenuItem '2' 'Limpar componentes substituidos (StartComponentCleanup)' -Recommended Write-MenuItem '3' 'Limpeza profunda /ResetBase (deixa de ser possivel desinstalar updates)' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { [void](Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /AnalyzeComponentStore') } '2' { $b = Get-SystemFreeBytes [void](Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /StartComponentCleanup') Write-CleanSummary $b } '3' { Write-Warn 'ResetBase torna permanentes todas as atualizacoes instaladas.' if (Confirm-Action 'Confirmar limpeza com /ResetBase?') { $b = Get-SystemFreeBytes [void](Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /StartComponentCleanup /ResetBase') Write-CleanSummary $b } } } } function Invoke-CleanMgr { Write-Section 'Limpeza de Disco do Windows (cleanmgr) automatica' $root = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches' if (-not (Test-Path $root) -or -not (Get-Command cleanmgr.exe -ErrorAction SilentlyContinue)) { Write-Warn 'cleanmgr nao disponivel neste sistema.' return } # Nunca limpar a pasta Transferencias do cliente $exclude = @('DownloadsFolder') if (Test-Path "$env:SystemDrive\Windows.old") { Write-Warn 'Existe Windows.old (instalacao anterior).' if (-not (Confirm-Action 'Remover Windows.old? (deixa de ser possivel reverter a atualizacao)')) { $exclude += 'Previous Installations' } } $handlers = @(Get-ChildItem -Path $root -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -notin $exclude }) foreach ($h in $handlers) { New-ItemProperty -Path $h.PSPath -Name StateFlags0777 -Value 2 -PropertyType DWord -Force -ErrorAction SilentlyContinue | Out-Null } Write-Info "Categorias selecionadas: $($handlers.Count) (Transferencias excluidas)." Write-Info 'A executar cleanmgr - pode abrir uma janela de progresso. Aguarde.' $b = Get-SystemFreeBytes [void](Invoke-Native 'cleanmgr.exe' '/sagerun:777') foreach ($h in $handlers) { Remove-ItemProperty -Path $h.PSPath -Name StateFlags0777 -ErrorAction SilentlyContinue } Write-CleanSummary $b } function Find-PSCLargeFiles { Write-Section 'Ficheiros grandes (>= 1 GB) nos perfis de utilizador' Write-Info 'A procurar (ficheiros so na cloud/OneDrive sao ignorados)...' $big = @(foreach ($p in (Get-PSCProfiles)) { Get-PSCFilesSafe -Root $p | Where-Object { $_.Length -ge 1GB -and (([int]$_.Attributes -band 0x441000) -eq 0) } }) | Sort-Object Length -Descending if ($big.Count -eq 0) { Write-Ok 'Nenhum ficheiro >= 1 GB encontrado nos perfis.'; return } Write-Host '' foreach ($f in ($big | Select-Object -First 25)) { Write-Host (' {0,10} ' -f (Format-Bytes $f.Length)) -NoNewline -ForegroundColor Yellow Write-Host ('{0:dd-MM-yyyy} ' -f $f.LastWriteTime) -NoNewline -ForegroundColor DarkGray Write-Host (Format-Short $f.FullName 85) -ForegroundColor White } $sum = ($big | Measure-Object -Property Length -Sum).Sum Write-Host '' Write-KV 'Total em ficheiros grandes' ("{0} ({1} ficheiros)" -f (Format-Bytes $sum), $big.Count) 'White' $csv = Join-Path $script:PSC.LogDir ("Ficheiros-grandes_{0}.csv" -f (Get-Date -Format 'yyyyMMdd_HHmmss')) $big | Select-Object @{ n = 'TamanhoGB'; e = { [math]::Round($_.Length / 1GB, 2) } }, LastWriteTime, FullName | Export-Csv -Path $csv -NoTypeInformation -Encoding UTF8 -Delimiter ';' Write-Info "Lista exportada: $csv" Write-Warn 'So leitura - confirme sempre com o cliente antes de apagar ficheiros pessoais.' } function Invoke-RecommendedCleanup { Write-Section 'Limpeza recomendada' Write-Info 'So categorias seguras. NAO toca em Documentos, Transferencias, cookies ou passwords.' $res = Show-CleanAnalysis $rec = @($res | Where-Object { $_.Cat.Rec -and $_.Bytes -gt 0 }) $recBytes = ($rec | Measure-Object -Property Bytes -Sum).Sum $before = Get-SystemFreeBytes if ($rec.Count -gt 0 -and (Confirm-Action ("Limpar {0} das categorias recomendadas (*)?" -f (Format-Bytes $recBytes)))) { foreach ($r in $rec) { [void](Clear-PSCCategory $r.Cat) } } $rb = $res | Where-Object { $_.Cat.Id -eq 'RECYCLE' } if ($rb -and $rb.Bytes -gt 0) { if (Confirm-Action ("Esvaziar Reciclagem ({0})? Confirme com o cliente" -f (Format-Bytes $rb.Bytes))) { [void](Clear-PSCCategory $rb.Cat) } } if (Confirm-Action 'Executar limpeza de componentes do Windows (DISM, 5-15 min)?') { [void](Invoke-Native 'DISM.exe' '/Online /Cleanup-Image /StartComponentCleanup') } Write-CleanSummary $before } function Show-CleanSelect { $res = Show-CleanAnalysis $sel = Read-Choice 'Numeros separados por virgula, T = todas, 0 = voltar' if ($sel -eq '0' -or $sel -eq '') { return } $targets = @() if ($sel -eq 'T') { $targets = @($res) } else { foreach ($n in ($sel -split '[,; ]+')) { if ($n -match '^\d+$' -and [int]$n -ge 1 -and [int]$n -le $res.Count) { $targets += $res[[int]$n - 1] } } } $targets = @($targets | Where-Object { $_.Bytes -gt 0 }) if ($targets.Count -eq 0) { Write-Warn 'Nada a limpar na selecao.'; return } Write-Host '' $targets | ForEach-Object { Write-Host (' - {0} ({1})' -f $_.Cat.Name, (Format-Bytes $_.Bytes)) -ForegroundColor Gray } if (-not (Confirm-Action 'Confirmar limpeza?')) { return } $before = Get-SystemFreeBytes foreach ($t in $targets) { [void](Clear-PSCCategory $t.Cat) } Write-CleanSummary $before } function Show-CleanupMenu { while ($true) { Show-Header Write-Host '' Write-Host ' LIMPEZA PROFUNDA' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Limpeza recomendada (Analise + categorias seguras + componentes)' -Recommended Write-MenuItem '2' 'Analisar espaco recuperavel (so leitura)' Write-MenuItem '3' 'Escolher categorias a limpar' Write-Host '' Write-MenuItem '4' 'Componentes do Windows - WinSxS (DISM)' Write-MenuItem '5' 'Limpeza de Disco do Windows automatica (cleanmgr / Windows.old)' Write-MenuItem '6' 'Esvaziar Reciclagem' Write-MenuItem '7' 'Encontrar ficheiros grandes (>= 1 GB) nos perfis' Write-Host '' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Invoke-RecommendedCleanup; Wait-Return } '2' { [void](Show-CleanAnalysis); Wait-Return } '3' { Show-CleanSelect; Wait-Return } '4' { Invoke-ComponentCleanup; Wait-Return } '5' { Invoke-CleanMgr; Wait-Return } '6' { $cat = Get-PSCCleanCategories | Where-Object { $_.Id -eq 'RECYCLE' } if (Confirm-Action 'Esvaziar a Reciclagem de todos os discos? Confirme com o cliente') { $b = Get-SystemFreeBytes; [void](Clear-PSCCategory $cat); Write-CleanSummary $b } Wait-Return } '7' { Find-PSCLargeFiles; Wait-Return } '0' { return } default { } } } } # ================================================================ # MODULO 4 - DIAGNOSTICO E HARDWARE # ================================================================ function Show-HardwareSummary { Write-Section 'Ficha Tecnica de Hardware' Write-Log '--- FICHA DE HARDWARE ---' $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue $bios = Get-CimInstance Win32_BIOS -ErrorAction SilentlyContinue $bb = Get-CimInstance Win32_BaseBoard -ErrorAction SilentlyContinue $cpus = @(Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue) $mems = @(Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue) $gpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue) Write-KV 'Fabricante / Modelo' ("{0} | {1}" -f $cs.Manufacturer, $cs.Model) 'White' Write-KV 'Numero de Serie (BIOS)' ([string]$bios.SerialNumber) 'Cyan' if ($bb) { Write-KV 'Motherboard' ("{0} {1}" -f $bb.Manufacturer, $bb.Product) } $biosDate = if ($bios.ReleaseDate) { '{0:dd-MM-yyyy}' -f $bios.ReleaseDate } else { 'n/d' } Write-KV 'BIOS' ("{0} ({1})" -f $bios.SMBIOSBIOSVersion, $biosDate) # UEFI + SecureBoot + TPM $fwType = if ($env:firmware_type) { $env:firmware_type } else { 'n/d' } $sbState = try { if (Confirm-SecureBootUEFI -ErrorAction Stop) { 'ATIVO' } else { 'INATIVO' } } catch { 'Nao suportado / Legacy' } Write-KV 'Firmware / Secure Boot' ("{0} | Secure Boot: {1}" -f $fwType, $sbState) $tpm = Get-CimInstance -Namespace 'root\CIMV2\Security\MicrosoftTpm' -ClassName Win32_Tpm -ErrorAction SilentlyContinue if ($tpm) { $tpmVer = [string]$tpm.SpecVersion.Split(',')[0] Write-KV 'TPM' ("v{0} (Ativo: {1})" -f $tpmVer, $tpm.IsEnabled_InitialValue) } else { Write-KV 'TPM' 'Nao detetado' 'Yellow' } foreach ($c in $cpus) { Write-KV 'Processador (CPU)' ("{0} ({1}C/{2}T @ {3} MHz)" -f $c.Name.Trim(), $c.NumberOfCores, $c.NumberOfLogicalProcessors, $c.MaxClockSpeed) 'White' } $totalRamGB = [math]::Round((($mems | Measure-Object -Property Capacity -Sum).Sum) / 1GB, 1) Write-KV 'Memoria RAM Total' ("{0} GB ({1} modulo(s) instalado(s))" -f $totalRamGB, $mems.Count) 'White' foreach ($m in $mems) { $capGB = [math]::Round($m.Capacity / 1GB, 1) $speed = if ($m.ConfiguredClockSpeed) { $m.ConfiguredClockSpeed } else { $m.Speed } $mfg = if ($m.Manufacturer) { $m.Manufacturer.Trim() } else { 'Generico' } $part = if ($m.PartNumber) { $m.PartNumber.Trim() } else { '' } Write-KV (" Slot [{0}]" -f $m.DeviceLocator) ("{0} GB @ {1} MHz | {2} {3}" -f $capGB, $speed, $mfg, $part) } foreach ($g in $gpus) { $vram = if ($g.AdapterRAM -gt 0) { '{0:N1} GB' -f ($g.AdapterRAM / 1GB) } else { 'Partilhada/Dinamica' } Write-KV 'Placa Grafica (GPU)' ("{0} ({1}) | Driver {2}" -f $g.Name, $vram, $g.DriverVersion) } } function Show-DiskHealth { Write-Section 'Saude dos Discos e SMART' Write-Log '--- SAUDE DOS DISCOS ---' $disks = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | Sort-Object DeviceId) $predict = @{} Get-CimInstance -Namespace 'root\wmi' -ClassName MSStorageDriver_FailurePredictStatus -ErrorAction SilentlyContinue | ForEach-Object { $predict[$_.InstanceName] = $_.PredictFailure } if ($disks.Count -eq 0) { Write-Warn 'Nao foi possivel obter informacao via Storage API.' } foreach ($d in $disks) { $sizeGB = [math]::Round($d.Size / 1GB, 0) $healthColor = if ($d.HealthStatus -eq 'Healthy') { 'Green' } else { 'Red' } Write-Host '' Write-KV ("Disco #{0}" -f $d.DeviceId) ("{0} ({1} GB | {2} | {3})" -f $d.FriendlyName, $sizeGB, $d.MediaType, $d.BusType) 'White' Write-KV ' Estado SMART / Operacional' ("{0} / {1}" -f $d.HealthStatus, $d.OperationalStatus) $healthColor $rel = Get-StorageReliabilityCounter -PhysicalDisk $d -ErrorAction SilentlyContinue if ($rel) { if ($null -ne $rel.Temperature -and $rel.Temperature -gt 0) { $tColor = if ($rel.Temperature -ge 65) { 'Red' } elseif ($rel.Temperature -ge 50) { 'Yellow' } else { 'Gray' } Write-KV ' Temperatura' ("{0} C" -f $rel.Temperature) $tColor } if ($null -ne $rel.Wear -and $rel.Wear -ge 0) { $wColor = if ($rel.Wear -ge 80) { 'Red' } elseif ($rel.Wear -ge 50) { 'Yellow' } else { 'Gray' } Write-KV ' Desgaste SSD (Wear)' ("{0}% usado ({1}% vida util restante)" -f $rel.Wear, (100 - $rel.Wear)) $wColor } if ($null -ne $rel.PowerOnHours -and $rel.PowerOnHours -gt 0) { $days = [math]::Round($rel.PowerOnHours / 24, 0) Write-KV ' Horas ligado' ("{0} h (~{1} dias)" -f $rel.PowerOnHours, $days) } $rErr = if ($null -ne $rel.ReadErrorsTotal) { $rel.ReadErrorsTotal } else { 0 } $wErr = if ($null -ne $rel.WriteErrorsTotal) { $rel.WriteErrorsTotal } else { 0 } if ($rErr -gt 0 -or $wErr -gt 0) { Write-KV ' Erros Leitura / Escrita' ("Leitura: {0} | Escrita: {1}" -f $rErr, $wErr) 'Red' } } } if ($predict.Values -contains $true) { Write-Err 'ALERTA CRITICO: SMART preve falha iminente num disco! Fazer backup imediato.' } Write-Host '' Write-Host ' VOLUMES LOGICOS' -ForegroundColor DarkYellow $vols = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ErrorAction SilentlyContinue) foreach ($v in $vols) { if (-not $v.Size) { continue } $pctFree = [math]::Round(($v.FreeSpace / $v.Size) * 100, 1) $vColor = if ($pctFree -lt 10) { 'Red' } elseif ($pctFree -lt 20) { 'Yellow' } else { 'Gray' } Write-KV (" Unidade {0} ({1})" -f $v.DeviceID, $v.VolumeName) ("{0} livres de {1} ({2}% livre)" -f (Format-Bytes $v.FreeSpace), (Format-Bytes $v.Size), $pctFree) $vColor } } function Get-PSCBatteryDetails { $bat = @(Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue) if ($bat.Count -eq 0) { return $null } $designCap = 0 $fullCap = 0 $cycles = 0 $static = Get-CimInstance -Namespace 'root\wmi' -ClassName BatteryStaticData -ErrorAction SilentlyContinue | Select-Object -First 1 $full = Get-CimInstance -Namespace 'root\wmi' -ClassName BatteryFullChargedCapacity -ErrorAction SilentlyContinue | Select-Object -First 1 $cycle = Get-CimInstance -Namespace 'root\wmi' -ClassName BatteryCycleCount -ErrorAction SilentlyContinue | Select-Object -First 1 if ($static -and $static.DesignedCapacity -gt 0) { $designCap = [int]$static.DesignedCapacity } if ($full -and $full.FullChargedCapacity -gt 0) { $fullCap = [int]$full.FullChargedCapacity } if ($cycle -and $cycle.CycleCount -gt 0) { $cycles = [int]$cycle.CycleCount } # Fallback infalivel via powercfg /batteryreport /xml (funciona em ASUS, Lenovo, HP, Dell mesmo quando WMI falha) if ($designCap -le 0 -or $fullCap -le 0) { $tmpXml = Join-Path $env:TEMP ("psc_bat_{0}.xml" -f $PID) try { & powercfg.exe /batteryreport /xml /output "$tmpXml" 2>$null | Out-Null if (Test-Path $tmpXml) { [xml]$bx = Get-Content -Path $tmpXml -Encoding UTF8 -ErrorAction Stop $bNode = $bx.BatteryReport.Batteries.Battery | Select-Object -First 1 if ($bNode) { if ([int]$bNode.DesignCapacity -gt 0) { $designCap = [int]$bNode.DesignCapacity } if ([int]$bNode.FullChargeCapacity -gt 0) { $fullCap = [int]$bNode.FullChargeCapacity } if ($cycles -le 0 -and [int]$bNode.CycleCount -gt 0) { $cycles = [int]$bNode.CycleCount } } Remove-Item $tmpXml -Force -ErrorAction SilentlyContinue } } catch { Remove-Item $tmpXml -Force -ErrorAction SilentlyContinue } } $healthPct = if ($designCap -gt 0 -and $fullCap -gt 0) { [math]::Min(100, [math]::Round(($fullCap / $designCap) * 100, 1)) } else { -1 } $wearPct = if ($healthPct -ge 0) { [math]::Max(0, [math]::Round(100 - $healthPct, 1)) } else { -1 } [pscustomobject]@{ Name = $bat[0].Name ChargePct = $bat[0].EstimatedChargeRemaining DesignCap = $designCap FullCap = $fullCap HealthPct = $healthPct WearPct = $wearPct Cycles = $cycles } } function Show-BatteryHealth { param([switch]$OfferReport) Write-Section 'Diagnostico de Bateria' Write-Log '--- BATERIA ---' $bd = Get-PSCBatteryDetails if (-not $bd) { Write-Info 'Nenhuma bateria detetada (Desktop ou bateria desconetada).' return } Write-KV 'Bateria' ("{0} | Carga atual: {1}%" -f $bd.Name, $bd.ChargePct) 'White' if ($bd.DesignCap -gt 0 -and $bd.FullCap -gt 0) { $designWh = [math]::Round($bd.DesignCap / 1000, 1) $fullWh = [math]::Round($bd.FullCap / 1000, 1) $hColor = if ($bd.HealthPct -lt 60) { 'Red' } elseif ($bd.HealthPct -lt 80) { 'Yellow' } else { 'Green' } Write-KV 'Capacidade de Fabrica' ("{0} Wh ({1} mWh)" -f $designWh, $bd.DesignCap) Write-KV 'Capacidade Atual Maxima' ("{0} Wh ({1} mWh)" -f $fullWh, $bd.FullCap) Write-KV 'Saude da Bateria' ("{0}% (Desgaste: {1}%)" -f $bd.HealthPct, $bd.WearPct) $hColor } if ($bd.Cycles -gt 0) { Write-KV 'Ciclos de Carga' ([string]$bd.Cycles) } if ($OfferReport -and (Confirm-Action 'Gerar e abrir relatorio completo HTML da bateria (powercfg)?')) { $out = Join-Path $script:PSC.LogDir ("BatteryReport_{0}_{1}.html" -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd_HHmmss')) [void](Invoke-Native 'powercfg.exe' "/batteryreport /output `"$out`"") if (Test-Path $out) { Write-Ok "Relatorio guardado: $out" Start-Process $out } } } function Get-BugCheckName { param([int]$Code) if ($Code -eq 0) { return '0x0 (Desligamento sem codigo / Botao Power / Queda de energia ou NVMe)' } $hex = '0x{0:X}' -f $Code $map = @{ '0x124' = 'WHEA_UNCORRECTABLE_ERROR (Falha Hardware: SSD NVMe PCIe / CPU / Temperatura)' '0x9F' = 'DRIVER_POWER_STATE_FAILURE (Driver bloqueou em Suspensao / Arranque Rapido)' '0xEF' = 'CRITICAL_PROCESS_DIED (Processo critico do Windows terminou - verificar SSD/SFC)' '0x7A' = 'KERNEL_DATA_INPAGE_ERROR (Falha de leitura no Disco / Paginacao)' '0xF4' = 'CRITICAL_OBJECT_TERMINATION (Disco deixou de responder)' '0x133' = 'DPC_WATCHDOG_VIOLATION (Driver NVMe/GPU/Wi-Fi congelou)' '0x1A' = 'MEMORY_MANAGEMENT (Erro de Memoria RAM / Paginacao)' '0x50' = 'PAGE_FAULT_IN_NONPAGED_AREA (RAM ou Driver corrompido)' '0x3B' = 'SYSTEM_SERVICE_EXCEPTION (Driver / GPU / Kernel)' '0xD1' = 'DRIVER_IRQL_NOT_LESS_OR_EQUAL (Driver de Rede/GPU)' '0x1E' = 'KMODE_EXCEPTION_NOT_HANDLED (Driver / Hardware)' '0x7E' = 'SYSTEM_THREAD_EXCEPTION_NOT_HANDLED (Driver)' '0x116' = 'VIDEO_TDR_FAILURE (Placa Grafica / Driver GPU congelou)' } if ($map.ContainsKey($hex)) { return "$hex - $($map[$hex])" } return "$hex (BugCheck codigo $Code)" } function Show-StabilityAndBSOD { Write-Section 'Estabilidade, BSODs e Eventos Criticos (ultimos 30 dias)' Write-Log '--- ESTABILIDADE E BSOD ---' $since = (Get-Date).AddDays(-30) # Minidumps existentes $dumps = @() foreach ($p in "$env:windir\Minidump", "$env:windir\MEMORY.DMP") { if (Test-Path $p) { $dumps += @(Get-ChildItem -Path $p -File -ErrorAction SilentlyContinue) } } $dColor = if ($dumps.Count -gt 0) { 'Yellow' } else { 'Green' } Write-KV 'Ficheiros Crash Dump' ("{0} encontrado(s)" -f $dumps.Count) $dColor foreach ($d in ($dumps | Sort-Object LastWriteTime -Descending | Select-Object -First 5)) { Write-KV (" Dump {0:dd-MM HH:mm}" -f $d.LastWriteTime) ("{0} ({1})" -f $d.Name, (Format-Bytes $d.Length)) 'Yellow' } # Eventos volmgr 161 (Falha ao criar o ficheiro de dump - tipico de SSD NVMe que cai a meio do BSOD 0%) $vol161 = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'volmgr'; Id = 161; StartTime = $since } -ErrorAction SilentlyContinue) if ($vol161.Count -gt 0) { Write-KV 'Falhas de Dump no Disco (volmgr 161)' ("{0} nos ultimos 30 dias (SSD desligou-se no BSOD 0%!)" -f $vol161.Count) 'Red' } # Kernel-Power 41 (desligamento inesperado + leitura forense do BugcheckCode interno) $kp41 = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power'; Id = 41; StartTime = $since } -ErrorAction SilentlyContinue) Write-KV 'Desligamentos abruptos (ID 41)' ("{0} nos ultimos 30 dias" -f $kp41.Count) $(if ($kp41.Count -gt 0) { 'Yellow' } else { 'Green' }) foreach ($ev in ($kp41 | Select-Object -First 5)) { try { $x = [xml]$ev.ToXml() $d = @{} $x.Event.EventData.Data | ForEach-Object { if ($_.Name) { $d[$_.Name] = $_.'#text' } } $bc = [int]$d['BugcheckCode'] $p1 = $d['BugcheckParameter1'] $desc = Get-BugCheckName $bc Write-KV (" ID 41 [{0:dd-MM HH:mm}]" -f $ev.TimeCreated) ("$desc | P1=$p1") $(if ($bc -ne 0) { 'Red' } else { 'Yellow' }) } catch { } } # BugChecks (WER SystemErrorReporting 1001) $bug = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting'; Id = 1001; StartTime = $since } -ErrorAction SilentlyContinue) Write-KV 'Ecras Azuis (BugCheck 1001)' ("{0} nos ultimos 30 dias" -f $bug.Count) $(if ($bug.Count -gt 0) { 'Red' } else { 'Green' }) foreach ($b in ($bug | Select-Object -First 5)) { $msg = ($b.Message -replace '\r|\n', ' ') Write-KV (" BSOD [{0:dd-MM HH:mm}]" -f $b.TimeCreated) (Format-Short $msg 75) 'Red' } # WHEA-Logger (erros fisicos de CPU/PCIe/RAM) $whea = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WHEA-Logger'; StartTime = $since } -ErrorAction SilentlyContinue) Write-KV 'Erros Hardware WHEA-Logger' ("{0} nos ultimos 30 dias" -f $whea.Count) $(if ($whea.Count -gt 0) { 'Red' } else { 'Green' }) # Erros de Disco / NTFS / Storahci / nvme $diskEv = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2, 3; ProviderName = 'disk', 'Ntfs', 'storahci', 'stornvme'; StartTime = $since } -MaxEvents 50 -ErrorAction SilentlyContinue) Write-KV 'Alertas de Disco/Controlador' ("{0} nos ultimos 30 dias" -f $diskEv.Count) $(if ($diskEv.Count -gt 0) { 'Red' } else { 'Green' }) # Ultimos crashes de aplicacoes (Event 1000 Application Error) $appErr = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = 'Application Error'; Id = 1000; StartTime = (Get-Date).AddDays(-7) } -MaxEvents 5 -ErrorAction SilentlyContinue) Write-KV 'Crashes de Aplicacoes (7d)' ("{0} recente(s)" -f $appErr.Count) foreach ($a in $appErr) { $firstLine = ($a.Message -split '\r?\n')[0] Write-Host (" - {0:dd-MM HH:mm} | {1}" -f $a.TimeCreated, (Format-Short $firstLine 75)) -ForegroundColor DarkGray } } function Show-NetworkDiagnostics { Write-Section 'Diagnostico de Rede e Conectividade' Write-Log '--- DIAGNOSTICO DE REDE ---' $configs = @(Get-CimInstance Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ErrorAction SilentlyContinue) if ($configs.Count -eq 0) { Write-Warn 'Nenhum adaptador com IP ativo.' } foreach ($c in $configs) { $ips = ($c.IPAddress | Where-Object { $_ -match '^\d+\.' }) -join ', ' $gw = if ($c.DefaultIPGateway) { $c.DefaultIPGateway -join ', ' } else { 'nenhum' } $dns = if ($c.DNSServerSearchOrder) { $c.DNSServerSearchOrder -join ', ' } else { 'nenhum' } Write-Host '' Write-Host (" Adaptador: {0}" -f $c.Description) -ForegroundColor White Write-KV ' MAC / DHCP' ("{0} | DHCP: {1}" -f $c.MACAddress, $c.DHCPEnabled) Write-KV ' IPv4 / Gateway' ("{0} | GW: {1}" -f $ips, $gw) 'Cyan' Write-KV ' Servidores DNS' $dns } Write-Host '' Write-Info 'A testar conectividade (Gateway, Cloudflare 1.1.1.1 e DNS)...' $gwIp = ($configs | Where-Object { $_.DefaultIPGateway } | Select-Object -First 1).DefaultIPGateway[0] if ($gwIp) { $pGw = Test-Connection -ComputerName $gwIp -Count 1 -ErrorAction SilentlyContinue if ($pGw) { Write-Ok ("Ping Gateway ({0}): {1} ms" -f $gwIp, $pGw.ResponseTime) } else { Write-Warn ("Ping Gateway ({0}): sem resposta" -f $gwIp) } } $pNet = Test-Connection -ComputerName '1.1.1.1' -Count 1 -ErrorAction SilentlyContinue if ($pNet) { Write-Ok ("Ligacao Internet (1.1.1.1): OK ({0} ms)" -f $pNet.ResponseTime) } else { Write-Err 'Ligacao Internet (1.1.1.1): FALHOU' } try { $null = [Net.Dns]::GetHostAddresses('proservicecomputer.pt') Write-Ok 'Resolucao DNS (proservicecomputer.pt): OK' } catch { Write-Err 'Resolucao DNS: FALHOU' } } function Show-LicenseAndSecurity { Write-Section 'Licenciamento Windows e Seguranca' Write-Log '--- LICENCIAMENTO E SEGURANCA ---' # Licenca Windows (so leitura) $lic = Get-CimInstance SoftwareLicensingProduct -Filter "ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f' AND PartialProductKey IS NOT NULL" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($lic) { $statusMap = @{ 0 = 'Nao licenciado'; 1 = 'ATIVADO (Licenciado)'; 2 = 'Periodo de graca OOB'; 3 = 'Periodo de graca OOT'; 4 = 'Nao genuino'; 5 = 'Notificacao'; 6 = 'Graca prolongada' } $stText = if ($statusMap.ContainsKey([int]$lic.LicenseStatus)) { $statusMap[[int]$lic.LicenseStatus] } else { "Codigo $($lic.LicenseStatus)" } $stColor = if ($lic.LicenseStatus -eq 1) { 'Green' } else { 'Yellow' } Write-KV 'Produto Windows' $lic.Name 'White' Write-KV 'Canal / Descricao' $lic.Description Write-KV 'Estado da Licenca' ("{0} (Final da chave: ...-{1})" -f $stText, $lic.PartialProductKey) $stColor } else { Write-Warn 'Nenhuma licenca ativa do Windows detetada.' } $sls = Get-CimInstance SoftwareLicensingService -ErrorAction SilentlyContinue if ($sls -and $sls.OA3xOriginalProductKey) { # v2.2.0: chave mascarada (so os ultimos 5 caracteres) para nao ir em claro para logs/portal $oemKey = [string]$sls.OA3xOriginalProductKey $oemMasked = if ($oemKey.Length -ge 5) { 'XXXXX-XXXXX-XXXXX-XXXXX-' + $oemKey.Substring($oemKey.Length - 5) } else { 'XXXXX' } Write-KV 'Chave OEM gravada na BIOS' ("{0} (mascarada)" -f $oemMasked) 'Cyan' } else { Write-KV 'Chave OEM na BIOS' 'Nao presente (licenca digital ou Retail)' 'DarkGray' } # Antivirus (SecurityCenter2) $avs = @(Get-CimInstance -Namespace 'root\SecurityCenter2' -ClassName AntiVirusProduct -ErrorAction SilentlyContinue) if ($avs.Count -gt 0) { foreach ($av in $avs) { Write-KV 'Antivirus registado' $av.displayName 'Green' } } else { Write-Warn 'Nenhum antivirus registado no SecurityCenter2.' } # BitLocker if (Get-Command Get-BitLockerVolume -ErrorAction SilentlyContinue) { $bl = Get-BitLockerVolume -MountPoint $env:SystemDrive -ErrorAction SilentlyContinue if ($bl) { Write-KV "BitLocker ($env:SystemDrive)" ("{0} ({1})" -f $bl.ProtectionStatus, $bl.VolumeStatus) } } } # ================================================================ # v2.2.0 - MOTOR DE DIAGNOSTICO (semaforo + nota 0-100 + recomendacoes) # Todas as verificacoes sao SO LEITURA. Falhas de verificacao ficam # registadas como N/D com o motivo (nunca sao silenciadas). # ================================================================ function Add-PSCCheck { param( [System.Collections.ArrayList]$List, [string]$Area, [string]$Check, [string]$Value, [string]$Status, [string]$Recommendation = '' ) [void]$List.Add([pscustomobject]@{ Area = $Area; Check = $Check; Value = $Value; Status = $Status; Recommendation = $Recommendation }) } function Invoke-PSCCheck { param([System.Collections.ArrayList]$List, [string]$Area, [string]$Check, [scriptblock]$Script) try { & $Script $List } catch { Add-PSCCheck $List $Area $Check ("Verificacao nao executada: {0}" -f $_.Exception.Message) 'ND' } } function Get-PSCDiagnosticResults { $r = New-Object System.Collections.ArrayList $since = (Get-Date).AddDays(-30) # --- ARMAZENAMENTO: discos fisicos (SMART, desgaste, temperatura) --- Invoke-PSCCheck $r 'Armazenamento' 'Saude dos discos (SMART)' { param($L) $disks = @(Get-PhysicalDisk -ErrorAction Stop | Sort-Object DeviceId) if ($disks.Count -eq 0) { Add-PSCCheck $L 'Armazenamento' 'Saude dos discos (SMART)' 'Sem dados da Storage API' 'ND'; return } $predict = $false Get-CimInstance -Namespace 'root\wmi' -ClassName MSStorageDriver_FailurePredictStatus -ErrorAction SilentlyContinue | ForEach-Object { if ($_.PredictFailure) { $predict = $true } } foreach ($d in $disks) { $rel = Get-StorageReliabilityCounter -PhysicalDisk $d -ErrorAction SilentlyContinue $wear = if ($rel -and $null -ne $rel.Wear) { [int]$rel.Wear } else { -1 } $temp = if ($rel -and $rel.Temperature -gt 0) { [int]$rel.Temperature } else { -1 } $errs = 0 if ($rel) { $errs = [int]$rel.ReadErrorsTotal + [int]$rel.WriteErrorsTotal } $sz = [math]::Round($d.Size / 1GB, 0) $val = "{0} ({1} GB, {2}/{3}) Estado: {4}" -f $d.FriendlyName, $sz, $d.MediaType, $d.BusType, $d.HealthStatus if ($wear -ge 0) { $val += " | Desgaste: $wear%" } if ($temp -ge 0) { $val += " | Temp: $temp C" } $st = 'OK'; $rec = '' if ($d.HealthStatus -ne 'Healthy' -or $predict) { $st = 'CRIT'; $rec = 'Disco com falha ou SMART a prever falha: fazer backup IMEDIATO dos dados e substituir o disco.' } elseif ($wear -ge 80) { $st = 'CRIT'; $rec = 'SSD com desgaste igual ou superior a 80%: substituir o SSD e clonar o sistema.' } elseif ($wear -ge 50) { $st = 'WARN'; $rec = 'SSD com desgaste a meio da vida util: planear substituicao e manter backups atualizados.' } elseif ($errs -gt 0) { $st = 'WARN'; $rec = 'O disco regista erros de leitura/escrita: verificar cabos/controlador e acompanhar de perto.' } elseif ($temp -ge 65) { $st = 'WARN'; $rec = 'Temperatura do disco elevada: limpar ventilacao e verificar fluxo de ar.' } Add-PSCCheck $L 'Armazenamento' ("Disco #{0}" -f $d.DeviceId) $val $st $rec } } # --- ARMAZENAMENTO: espaco livre nos volumes --- Invoke-PSCCheck $r 'Armazenamento' 'Espaco livre' { param($L) $vols = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ErrorAction Stop) foreach ($v in $vols) { if (-not $v.Size) { continue } $pct = [math]::Round(($v.FreeSpace / $v.Size) * 100, 1) $val = "{0} - {1} livres de {2} ({3}%)" -f $v.DeviceID, (Format-Bytes $v.FreeSpace), (Format-Bytes $v.Size), $pct $st = 'OK'; $rec = '' if ($pct -lt 10) { $st = 'CRIT'; $rec = "Unidade $($v.DeviceID) quase cheia: limpar ficheiros temporarios/duplicados ou aumentar a capacidade." } elseif ($pct -lt 20) { $st = 'WARN'; $rec = "Unidade $($v.DeviceID) com pouco espaco livre: executar limpeza de disco." } Add-PSCCheck $L 'Armazenamento' ("Volume {0}" -f $v.DeviceID) $val $st $rec } } # --- BATERIA --- Invoke-PSCCheck $r 'Energia' 'Bateria' { param($L) $bd = Get-PSCBatteryDetails if (-not $bd) { Add-PSCCheck $L 'Energia' 'Bateria' 'Sem bateria (desktop) ou desligada' 'INFO'; return } if ($bd.HealthPct -lt 0) { Add-PSCCheck $L 'Energia' 'Bateria' ("Presente ({0}%) mas sem dados de capacidade" -f $bd.ChargePct) 'ND'; return } $val = "Saude {0}% | Capacidade atual {1} mWh de {2} mWh | Ciclos: {3}" -f $bd.HealthPct, $bd.FullCap, $bd.DesignCap, $bd.Cycles $st = 'OK'; $rec = '' if ($bd.HealthPct -lt 60) { $st = 'CRIT'; $rec = 'Bateria muito degradada (abaixo de 60%): substituir a bateria.' } elseif ($bd.HealthPct -lt 80) { $st = 'WARN'; $rec = 'Bateria com desgaste moderado: autonomia reduzida, considerar substituicao.' } Add-PSCCheck $L 'Energia' 'Bateria' $val $st $rec } # --- ESTABILIDADE: BSOD, desligamentos abruptos, WHEA, disco --- Invoke-PSCCheck $r 'Estabilidade' 'Ecras azuis (30 dias)' { param($L) $bug = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting'; Id = 1001; StartTime = (Get-Date).AddDays(-30) } -ErrorAction SilentlyContinue) $st = 'OK'; $rec = '' if ($bug.Count -ge 3) { $st = 'CRIT'; $rec = 'Ecras azuis repetidos: diagnosticar drivers, RAM e disco (analisar minidumps).' } elseif ($bug.Count -gt 0) { $st = 'WARN'; $rec = 'Ocorreram ecras azuis: analisar o codigo de erro e atualizar drivers.' } Add-PSCCheck $L 'Estabilidade' 'Ecras azuis (30 dias)' ("{0} ocorrencia(s)" -f $bug.Count) $st $rec } Invoke-PSCCheck $r 'Estabilidade' 'Desligamentos abruptos (ID 41)' { param($L) $kp = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power'; Id = 41; StartTime = (Get-Date).AddDays(-30) } -ErrorAction SilentlyContinue) $st = 'OK'; $rec = '' if ($kp.Count -ge 3) { $st = 'WARN'; $rec = 'Varios desligamentos inesperados: verificar fonte de alimentacao, bateria, temperatura e SSD.' } elseif ($kp.Count -gt 0) { $st = 'INFO' } Add-PSCCheck $L 'Estabilidade' 'Desligamentos abruptos (ID 41)' ("{0} ocorrencia(s)" -f $kp.Count) $st $rec } Invoke-PSCCheck $r 'Estabilidade' 'Erros de hardware (WHEA)' { param($L) $w = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WHEA-Logger'; StartTime = (Get-Date).AddDays(-30) } -ErrorAction SilentlyContinue) $st = 'OK'; $rec = '' if ($w.Count -gt 0) { $st = 'CRIT'; $rec = 'Erros fisicos de CPU/RAM/PCIe registados: testar a memoria (MemTest) e verificar temperaturas e SSD NVMe.' } Add-PSCCheck $L 'Estabilidade' 'Erros de hardware (WHEA)' ("{0} evento(s)" -f $w.Count) $st $rec } Invoke-PSCCheck $r 'Estabilidade' 'Erros de disco / controlador' { param($L) $de = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2, 3; ProviderName = 'disk', 'Ntfs', 'storahci', 'stornvme'; StartTime = (Get-Date).AddDays(-30) } -MaxEvents 50 -ErrorAction SilentlyContinue) $st = 'OK'; $rec = '' if ($de.Count -gt 0) { $st = 'WARN'; $rec = 'Alertas do subsistema de disco: correr verificacao do disco (chkdsk) e validar o SMART.' } Add-PSCCheck $L 'Estabilidade' 'Erros de disco / controlador' ("{0} evento(s)" -f $de.Count) $st $rec } # --- MEMORIA --- Invoke-PSCCheck $r 'Hardware' 'Memoria RAM' { param($L) $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction Stop $gb = [math]::Round($cs.TotalPhysicalMemory / 1GB, 1) $st = 'OK'; $rec = '' if ($gb -lt 4) { $st = 'CRIT'; $rec = 'Menos de 4 GB de RAM: upgrade de memoria necessario para um desempenho aceitavel.' } elseif ($gb -lt 8) { $st = 'WARN'; $rec = 'Menos de 8 GB de RAM: recomendado upgrade para 8 GB ou mais.' } Add-PSCCheck $L 'Hardware' 'Memoria RAM' ("{0} GB instalados" -f $gb) $st $rec } # --- DRIVERS COM ERRO --- Invoke-PSCCheck $r 'Sistema' 'Drivers / dispositivos com erro' { param($L) $bad = @(Get-CimInstance Win32_PnPEntity -Filter 'ConfigManagerErrorCode<>0' -ErrorAction Stop) $st = 'OK'; $rec = '' $names = '' if ($bad.Count -gt 0) { $st = 'WARN' $names = ' | ' + ((@($bad | Select-Object -First 3 | ForEach-Object { $_.Name })) -join '; ') $rec = 'Dispositivos sem driver ou com erro no Gestor de Dispositivos: instalar/atualizar os drivers.' } Add-PSCCheck $L 'Sistema' 'Drivers / dispositivos com erro' ("{0} dispositivo(s){1}" -f $bad.Count, $names) $st $rec } # --- REINICIO PENDENTE --- Invoke-PSCCheck $r 'Sistema' 'Reinicio pendente' { param($L) if (Test-PendingReboot) { Add-PSCCheck $L 'Sistema' 'Reinicio pendente' 'Sim' 'WARN' 'Reiniciar o equipamento para concluir atualizacoes pendentes.' } else { Add-PSCCheck $L 'Sistema' 'Reinicio pendente' 'Nao' 'OK' } } # --- VERSAO DO WINDOWS --- Invoke-PSCCheck $r 'Sistema' 'Versao do Windows' { param($L) $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop $b = [int]$os.BuildNumber $val = "{0} (build {1})" -f ($os.Caption -replace '^Microsoft\s+', ''), $b if ($b -lt 22000) { Add-PSCCheck $L 'Sistema' 'Versao do Windows' $val 'WARN' 'Windows 10 ja sem atualizacoes de seguranca gratuitas (fim de suporte em 14/10/2025): migrar para Windows 11 se o hardware permitir.' } else { Add-PSCCheck $L 'Sistema' 'Versao do Windows' $val 'OK' } } # --- ARRANQUE --- Invoke-PSCCheck $r 'Desempenho' 'Programas no arranque' { param($L) $n = @(Get-CimInstance Win32_StartupCommand -ErrorAction Stop).Count if ($n -gt 15) { Add-PSCCheck $L 'Desempenho' 'Programas no arranque' ("{0} itens" -f $n) 'WARN' 'Demasiados programas no arranque: desativar os desnecessarios para acelerar o arranque.' } else { Add-PSCCheck $L 'Desempenho' 'Programas no arranque' ("{0} itens" -f $n) 'OK' } } # --- SEGURANCA: antivirus, Defender, firewall --- Invoke-PSCCheck $r 'Seguranca' 'Antivirus' { param($L) $avs = @(Get-CimInstance -Namespace 'root\SecurityCenter2' -ClassName AntiVirusProduct -ErrorAction Stop) if ($avs.Count -eq 0) { Add-PSCCheck $L 'Seguranca' 'Antivirus' 'Nenhum antivirus registado' 'CRIT' 'Sem antivirus ativo: instalar/ativar proteccao antivirus.'; return } $names = (@($avs | ForEach-Object { $_.displayName }) -join ', ') Add-PSCCheck $L 'Seguranca' 'Antivirus' $names 'OK' } Invoke-PSCCheck $r 'Seguranca' 'Defender: assinaturas' { param($L) $mp = Get-MpComputerStatus -ErrorAction Stop $age = [int]$mp.AntivirusSignatureAge $val = "Tempo real: {0} | Assinaturas com {1} dia(s)" -f $mp.RealTimeProtectionEnabled, $age if ($age -gt 7) { Add-PSCCheck $L 'Seguranca' 'Defender: assinaturas' $val 'WARN' 'Assinaturas do Defender desatualizadas: atualizar a proteccao.' } else { Add-PSCCheck $L 'Seguranca' 'Defender: assinaturas' $val 'OK' } } Invoke-PSCCheck $r 'Seguranca' 'Firewall do Windows' { param($L) $fw = @(Get-NetFirewallProfile -ErrorAction Stop) $off = @($fw | Where-Object { -not $_.Enabled }) if ($off.Count -gt 0) { Add-PSCCheck $L 'Seguranca' 'Firewall do Windows' ("Desativada em: {0}" -f ((@($off | ForEach-Object { $_.Name })) -join ', ')) 'WARN' 'Firewall desativada em algum perfil: reativar salvo se existir firewall de terceiros.' } else { Add-PSCCheck $L 'Seguranca' 'Firewall do Windows' 'Ativa em todos os perfis' 'OK' } } Invoke-PSCCheck $r 'Seguranca' 'Secure Boot / TPM' { param($L) $sb = $null try { $sb = Confirm-SecureBootUEFI -ErrorAction Stop } catch { $sb = $null } $tpm = Get-CimInstance -Namespace 'root\CIMV2\Security\MicrosoftTpm' -ClassName Win32_Tpm -ErrorAction SilentlyContinue $tpmTxt = if ($tpm) { 'TPM v' + [string]($tpm.SpecVersion -split ',')[0] } else { 'TPM nao detetado' } $sbTxt = if ($null -eq $sb) { 'Secure Boot n/d (Legacy)' } elseif ($sb) { 'Secure Boot ativo' } else { 'Secure Boot inativo' } $st = 'OK'; $rec = '' if (-not $tpm -or $sb -ne $true) { $st = 'INFO'; $rec = '' } Add-PSCCheck $L 'Seguranca' 'Secure Boot / TPM' ("{0} | {1}" -f $tpmTxt, $sbTxt) $st $rec } # --- LICENCA WINDOWS --- Invoke-PSCCheck $r 'Sistema' 'Licenca do Windows' { param($L) $lic = Get-CimInstance SoftwareLicensingProduct -Filter "ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f' AND PartialProductKey IS NOT NULL" -ErrorAction Stop | Select-Object -First 1 if (-not $lic) { Add-PSCCheck $L 'Sistema' 'Licenca do Windows' 'Nenhuma licenca ativa' 'WARN' 'Windows sem licenca ativa: regularizar o licenciamento.'; return } if ($lic.LicenseStatus -eq 1) { Add-PSCCheck $L 'Sistema' 'Licenca do Windows' ("Ativado (...-{0})" -f $lic.PartialProductKey) 'OK' } else { Add-PSCCheck $L 'Sistema' 'Licenca do Windows' ("Estado {0} (...-{1})" -f $lic.LicenseStatus, $lic.PartialProductKey) 'WARN' 'Windows nao ativado: regularizar o licenciamento.' } } # --- REDE --- Invoke-PSCCheck $r 'Rede' 'Gateway / Internet / DNS' { param($L) $cfg = @(Get-CimInstance Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ErrorAction Stop) $gwCfg = $cfg | Where-Object { $_.DefaultIPGateway } | Select-Object -First 1 if (-not $gwCfg) { Add-PSCCheck $L 'Rede' 'Ligacao de rede' 'Sem adaptador com gateway' 'WARN' 'Sem ligacao de rede ativa: verificar cabo/Wi-Fi e adaptador.'; return } $gw = [string]$gwCfg.DefaultIPGateway[0] $okGw = Test-Connection -ComputerName $gw -Count 2 -Quiet -ErrorAction SilentlyContinue $okNet = Test-Connection -ComputerName '1.1.1.1' -Count 2 -Quiet -ErrorAction SilentlyContinue $okDns = $true try { $null = [Net.Dns]::GetHostAddresses('proservicecomputer.pt') } catch { $okDns = $false } $val = "Gateway {0}: {1} | Internet: {2} | DNS: {3}" -f $gw, $(if ($okGw) { 'OK' } else { 'FALHA' }), $(if ($okNet) { 'OK' } else { 'FALHA' }), $(if ($okDns) { 'OK' } else { 'FALHA' }) if (-not $okGw) { Add-PSCCheck $L 'Rede' 'Gateway / Internet / DNS' $val 'CRIT' 'Gateway sem resposta: verificar router, cabo e configuracao IP.' } elseif (-not $okNet) { Add-PSCCheck $L 'Rede' 'Gateway / Internet / DNS' $val 'WARN' 'Sem acesso a Internet: verificar o router/operador.' } elseif (-not $okDns) { Add-PSCCheck $L 'Rede' 'Gateway / Internet / DNS' $val 'WARN' 'Resolucao DNS com falhas: verificar servidores DNS.' } else { Add-PSCCheck $L 'Rede' 'Gateway / Internet / DNS' $val 'OK' } } return $r } function Get-PSCScore { param($Results) $crit = @($Results | Where-Object { $_.Status -eq 'CRIT' }).Count $warn = @($Results | Where-Object { $_.Status -eq 'WARN' }).Count $ok = @($Results | Where-Object { $_.Status -eq 'OK' }).Count $s = 100 - ($crit * 20) - ($warn * 6) if ($s -lt 0) { $s = 0 } $label = if ($crit -gt 0 -or $s -lt 60) { 'CRITICO' } elseif ($warn -gt 0 -or $s -lt 85) { 'ATENCAO' } else { 'BOM ESTADO' } [pscustomobject]@{ Score = $s; Crit = $crit; Warn = $warn; Ok = $ok; Label = $label } } function Show-PSCDiagnosticScore { Write-Section 'Semaforo de Diagnostico e Nota Global (v2.2)' Write-Info 'A executar verificacoes (pode demorar 20 a 40 segundos)...' $diag = Get-PSCDiagnosticResults $script:PSCDiag = $diag foreach ($c in $diag) { $tag = switch ($c.Status) { 'OK' { '[ OK ]' } 'WARN' { '[ !! ]' } 'CRIT' { '[CRIT]' } 'INFO' { '[info]' } default { '[ n/d]' } } $col = switch ($c.Status) { 'OK' { 'Green' } 'WARN' { 'Yellow' } 'CRIT' { 'Red' } 'INFO' { 'Cyan' } default { 'DarkGray' } } Write-Host (" {0} {1,-13} {2,-30} {3}" -f $tag, $c.Area, (Format-Short $c.Check 30), (Format-Short $c.Value 70)) -ForegroundColor $col Write-Log ("DIAG [{0}] {1} | {2} | {3}" -f $c.Status, $c.Area, $c.Check, $c.Value) } $sc = Get-PSCScore $diag $scCol = if ($sc.Label -eq 'CRITICO') { 'Red' } elseif ($sc.Label -eq 'ATENCAO') { 'Yellow' } else { 'Green' } Write-Host '' Write-Host (" NOTA GLOBAL: {0}/100 - {1} (Critico: {2} | Atencao: {3} | Conforme: {4})" -f $sc.Score, $sc.Label, $sc.Crit, $sc.Warn, $sc.Ok) -ForegroundColor $scCol Write-Log ("DIAG NOTA GLOBAL: {0}/100 - {1}" -f $sc.Score, $sc.Label) $recs = @($diag | Where-Object { ($_.Status -eq 'CRIT' -or $_.Status -eq 'WARN') -and $_.Recommendation }) if ($recs.Count -gt 0) { Write-Host '' Write-Host ' RECOMENDACOES (por prioridade):' -ForegroundColor DarkYellow foreach ($x in ($recs | Sort-Object @{ Expression = { if ($_.Status -eq 'CRIT') { 0 } else { 1 } } })) { $rc = if ($x.Status -eq 'CRIT') { 'Red' } else { 'Yellow' } Write-Host (" - [{0}] {1}: {2}" -f $x.Status, $x.Check, $x.Recommendation) -ForegroundColor $rc Write-Log ("DIAG RECOMENDACAO [{0}] {1}: {2}" -f $x.Status, $x.Check, $x.Recommendation) } } } function Invoke-FullDiagnostics { Show-HardwareSummary Show-DiskHealth Show-BatteryHealth Show-StabilityAndBSOD Show-NetworkDiagnostics Show-LicenseAndSecurity Show-PSCDiagnosticScore Write-Host '' Write-Ok "Diagnostico completo registado no log: $($script:LogFile)" if (Confirm-Action 'Enviar este Raio-X Completo + Log agora para o Portal PSC / Antigravity?') { Send-PSCLogsToPortal } } function Show-DiagnosticsMenu { while ($true) { Show-Header Write-Host '' Write-Host ' DIAGNOSTICO E HARDWARE (SO LEITURA)' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Diagnostico completo de bancada (Hardware + SMART + Bateria + BSOD + Licenca)' -Recommended Write-Host '' Write-MenuItem '2' 'Ficha tecnica de hardware (CPU, RAM por slot, Board, BIOS, GPU, TPM)' Write-MenuItem '3' 'Saude dos discos e SMART (temperatura, desgaste SSD, horas ligado)' Write-MenuItem '4' 'Saude da bateria + relatorio HTML (powercfg /batteryreport)' Write-MenuItem '5' 'Historico de BSODs, desligamentos abruptos e erros criticos (30 dias)' Write-MenuItem '6' 'Diagnostico de rede e conectividade (IP, Gateway, DNS, Ping)' Write-MenuItem '7' 'Estado da licenca Windows (chave OEM BIOS), Antivirus e BitLocker' Write-MenuItem '8' 'Abrir Diagnostico de Memoria RAM do Windows (mdsched.exe)' Write-MenuItem '9' 'Semaforo de diagnostico + Nota Global 0-100 + Recomendacoes (v2.2)' -Recommended Write-Host '' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Invoke-FullDiagnostics; Wait-Return } '2' { Show-HardwareSummary; Wait-Return } '3' { Show-DiskHealth; Wait-Return } '4' { Show-BatteryHealth -OfferReport; Wait-Return } '5' { Show-StabilityAndBSOD; Wait-Return } '6' { Show-NetworkDiagnostics; Wait-Return } '7' { Show-LicenseAndSecurity; Wait-Return } '8' { Start-Process 'mdsched.exe' } '9' { Show-PSCDiagnosticScore; Wait-Return } '0' { return } default { } } } } # ================================================================ # MODULO 5 - POS-INSTALACAO (MOTOR DIRETO CDN + AUTO-REPAIR WINGET) # ================================================================ function Repair-PSCWinget { Write-Section 'Reparar / Ativar Gestor de Pacotes Winget num PC Novo' Write-Log '=== INICIO: Reparacao / Bootstrap Winget ===' # 1. Procurar winget.exe escondido em WindowsApps (comum quando corre como Admin num PC acabado de formatar) $winAppsPath = Join-Path $env:ProgramFiles 'WindowsApps' $foundWinget = Get-ChildItem -Path $winAppsPath -Filter 'winget.exe' -Recurse -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($foundWinget) { $dir = $foundWinget.DirectoryName if ($env:PATH -notlike "*$dir*") { $env:PATH = "$dir;$env:PATH" } Write-Ok "Binario winget localizado e adicionado ao PATH: $($foundWinget.FullName)" } # 2. Se mesmo assim nao existir winget, descarregar e instalar App Installer oficial da Microsoft if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { Write-Info 'Winget ausente neste Windows. A descarregar Microsoft DesktopAppInstaller oficial (aka.ms/getwinget)...' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' $vclibsUrl = 'https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx' $vclibsPkg = Join-Path $env:TEMP 'Microsoft.VCLibs.x64.14.00.Desktop.appx' Invoke-WebRequest -Uri $vclibsUrl -OutFile $vclibsPkg -UseBasicParsing -TimeoutSec 60 -ErrorAction SilentlyContinue if (Test-Path $vclibsPkg) { Add-AppxPackage -Path $vclibsPkg -ErrorAction SilentlyContinue } $wingetUrl = 'https://aka.ms/getwinget' $wingetPkg = Join-Path $env:TEMP 'Microsoft.DesktopAppInstaller.msixbundle' Invoke-WebRequest -Uri $wingetUrl -OutFile $wingetPkg -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop $ProgressPreference = $prevProg Add-AppxPackage -Path $wingetPkg -ErrorAction Stop Write-Ok 'Pacote Microsoft DesktopAppInstaller (winget) instalado com sucesso!' $foundWinget = Get-ChildItem -Path $winAppsPath -Filter 'winget.exe' -Recurse -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($foundWinget) { $env:PATH = "$($foundWinget.DirectoryName);$env:PATH" } } catch { $ProgressPreference = 'Continue' Write-Warn "Nao foi possivel instalar o winget automaticamente: $($_.Exception.Message)" } } # 3. Corrigir erro de certificado / fontes do winget (0x8a15005e) em PCs novos if (Get-Command winget.exe -ErrorAction SilentlyContinue) { Write-Info 'A atualizar e reparar origens do catalogo winget (source reset / update)...' [void](Invoke-Native 'winget.exe' 'source reset --force') [void](Invoke-Native 'winget.exe' 'source update') Write-Ok 'Winget pronto e operacional!' return $true } return $false } function Test-WingetAvailable { if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return $true } # Tentar localizar automaticamente em WindowsApps antes de desistir $winAppsPath = Join-Path $env:ProgramFiles 'WindowsApps' $foundWinget = Get-ChildItem -Path $winAppsPath -Filter 'winget.exe' -Recurse -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($foundWinget) { $env:PATH = "$($foundWinget.DirectoryName);$env:PATH" if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return $true } } return (Repair-PSCWinget) } function Install-WingetPackage { param( [string]$Id, [string]$Name, [string]$Locale = '' ) if (-not (Test-WingetAvailable)) { Write-Warn "Winget indisponivel para instalar $Name." return $false } Write-Section "A instalar via Winget: $Name ($Id)" $baseArgs = "install --id $Id -e --silent --accept-package-agreements --accept-source-agreements --disable-interactivity" $argsWithLocale = if ($Locale) { "$baseArgs --locale $Locale" } else { $baseArgs } $code = Invoke-Native 'winget.exe' $argsWithLocale if ($code -ne 0 -and $Locale) { Write-Info "A tentar novamente sem restricao de idioma ($Name)..." $code = Invoke-Native 'winget.exe' $baseArgs } if ($code -ne 0 -and $code -ne -1978335189) { Write-Info 'A reparar fontes do winget (source reset) e tentar mais uma vez...' [void](Invoke-Native 'winget.exe' 'source reset --force') $code = Invoke-Native 'winget.exe' "$baseArgs --force" } # -1978335189 (0x8A15002B) = ja instalado e sem atualizacao disponivel if ($code -eq 0 -or $code -eq -1978335189) { Write-Ok "$Name instalado / atualizado com sucesso." return $true } Write-Warn "$Name terminou com codigo $code." return $false } function Install-ChromeDirect { Write-Section 'Google Chrome Enterprise x64 (Download Direto CDN Google - Sem Winget)' $msiUrl = 'https://dl.google.com/dl/chrome/install/googlechromestandaloneenterprise64.msi' $tempMsi = Join-Path $env:TEMP 'GoogleChromeEnterprise64.msi' Write-Info 'A descarregar GoogleChromeEnterprise64.msi diretamente dos servidores da Google...' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' Invoke-WebRequest -Uri $msiUrl -OutFile $tempMsi -UseBasicParsing -TimeoutSec 180 -ErrorAction Stop $ProgressPreference = $prevProg Write-Info 'A instalar Google Chrome silenciosamente para todos os utilizadores (msiexec /qn)...' $code = Invoke-Native 'msiexec.exe' "/i `"$tempMsi`" /qn /norestart" Remove-Item -Path $tempMsi -Force -ErrorAction SilentlyContinue if ($code -eq 0 -or $code -eq 3010) { Write-Ok 'Google Chrome instalado com sucesso (CDN Direto)!' Write-Log 'Google Chrome instalado via MSI Direto.' return $true } } catch { $ProgressPreference = 'Continue' Write-Warn "Download direto do Chrome falhou ($($_.Exception.Message)). A tentar via winget..." } return (Install-WingetPackage -Id 'Google.Chrome' -Name 'Google Chrome') } function Install-FirefoxPTDirect { Write-Section 'Mozilla Firefox PT-PT x64 (Download Direto CDN Mozilla - Sem Winget)' $ffUrl = 'https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=pt-PT' $tempExe = Join-Path $env:TEMP 'FirefoxSetup_pt-PT_x64.exe' Write-Info 'A descarregar Firefox mais recente (PT-PT x64) diretamente da Mozilla CDN...' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' Invoke-WebRequest -Uri $ffUrl -OutFile $tempExe -UseBasicParsing -TimeoutSec 180 -ErrorAction Stop $ProgressPreference = $prevProg Write-Info 'A instalar Mozilla Firefox (PT-PT) em modo silencioso (/S)...' $code = Invoke-Native $tempExe '/S' Remove-Item -Path $tempExe -Force -ErrorAction SilentlyContinue if ($code -eq 0) { Write-Ok 'Mozilla Firefox (PT-PT) instalado com sucesso (CDN Direto)!' Write-Log 'Mozilla Firefox PT-PT instalado via CDN Direto.' return $true } } catch { $ProgressPreference = 'Continue' Write-Warn "Download direto do Firefox falhou ($($_.Exception.Message)). A tentar via winget..." } return (Install-WingetPackage -Id 'Mozilla.Firefox' -Name 'Mozilla Firefox' -Locale 'pt-PT') } function Install-WinRARPTDirect { Write-Section 'WinRAR PT-PT x64 (Download Direto RARLab - Sem Winget)' $tempExe = Join-Path $env:TEMP 'winrar-x64-pt.exe' Write-Info 'A obter o instalador oficial WinRAR x64 em Portugues diretamente de rarlab.com...' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' # Deteta dinamicamente a versao mais recente PT na pagina oficial rarlab.com, com fallback para versoes conhecidas $rarUrls = @() try { $dlPage = (Invoke-WebRequest -Uri 'https://www.rarlab.com/download.htm' -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop).Content if ($dlPage -match 'href="(/rar/winrar-x64-\d+pt\.exe)"') { $rarUrls += ('https://www.rarlab.com' + $Matches[1]) } if ($dlPage -match 'href="(/rar/winrar-x64-\d+br\.exe)"') { $rarUrls += ('https://www.rarlab.com' + $Matches[1]) } } catch { } $rarUrls += @( 'https://www.rarlab.com/rar/winrar-x64-710pt.exe', 'https://www.rarlab.com/rar/winrar-x64-701pt.exe', 'https://www.rarlab.com/rar/winrar-x64-700pt.exe', 'https://www.rarlab.com/rar/winrar-x64-624pt.exe' ) $rarUrls = $rarUrls | Select-Object -Unique $downloaded = $false foreach ($u in $rarUrls) { try { Invoke-WebRequest -Uri $u -OutFile $tempExe -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop if ((Test-Path $tempExe) -and (Get-Item $tempExe).Length -gt 1000000) { $downloaded = $true Write-Info "Descarregado com sucesso de: $u" break } } catch { } } $ProgressPreference = $prevProg if ($downloaded) { Write-Info 'A instalar WinRAR (PT) silenciosamente (/S)...' $code = Invoke-Native $tempExe '/S' Remove-Item -Path $tempExe -Force -ErrorAction SilentlyContinue if ($code -eq 0) { Write-Ok 'WinRAR (PT) instalado com sucesso (CDN Direto)!' Write-Log 'WinRAR PT instalado via CDN Direto.' return $true } } } catch { $ProgressPreference = 'Continue' Write-Warn "Download direto do WinRAR falhou ($($_.Exception.Message)). A tentar via winget..." } return (Install-WingetPackage -Id 'RARLab.WinRAR' -Name 'WinRAR' -Locale 'pt-PT') } function Convert-PngToIcoFile { param( [Parameter(Mandatory)][string]$PngPath, [Parameter(Mandatory)][string]$IcoPath ) try { $pngBytes = [System.IO.File]::ReadAllBytes($PngPath) $ms = New-Object System.IO.MemoryStream $bw = New-Object System.IO.BinaryWriter($ms) # ICONDIR (6 bytes): Reserved=0, Type=1 (ICO), Count=1 $bw.Write([uint16]0) $bw.Write([uint16]1) $bw.Write([uint16]1) # ICONDIRENTRY (16 bytes): Width=0 (256+), Height=0 (256+), Colors=0, Reserved=0, Planes=1, Bpp=32, Size, Offset=22 $bw.Write([byte]0) $bw.Write([byte]0) $bw.Write([byte]0) $bw.Write([byte]0) $bw.Write([uint16]1) $bw.Write([uint16]32) $bw.Write([uint32]$pngBytes.Length) $bw.Write([uint32]22) # Payload PNG nativo (suportado pelo Explorer do Windows 10/11 em alta resolucao) $bw.Write($pngBytes) $bw.Flush() [System.IO.File]::WriteAllBytes($IcoPath, $ms.ToArray()) $bw.Close() $ms.Close() return (Test-Path -LiteralPath $IcoPath) } catch { return $false } } function Install-TeamViewerQSDesktop { Write-Section 'TeamViewer QuickSupport com Logotipo PSC (Ambiente de Trabalho)' $urlExe = 'https://download.teamviewer.com/download/TeamViewerQS.exe' $urlPng = 'https://proservicecomputer.pt/favicon.png' $pscSupportDir = 'C:\PSC\Suporte' if (-not (Test-Path -LiteralPath $pscSupportDir)) { New-Item -Path $pscSupportDir -ItemType Directory -Force | Out-Null } $exePath = Join-Path $pscSupportDir 'TeamViewerQS.exe' $pngPath = Join-Path $pscSupportDir 'psc-cube.png' $icoPath = Join-Path $pscSupportDir 'psc-logo.ico' $pubDesktop = [Environment]::GetFolderPath('CommonDesktopDirectory') if (-not $pubDesktop -or -not (Test-Path $pubDesktop)) { $pubDesktop = 'C:\Users\Public\Desktop' } Write-Info "A descarregar TeamViewerQS.exe para $exePath..." try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' Invoke-WebRequest -Uri $urlExe -OutFile $exePath -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop # Descarregar o Cubo Oficial PSC e converter para .ICO de alta definicao try { Invoke-WebRequest -Uri $urlPng -OutFile $pngPath -UseBasicParsing -TimeoutSec 30 -ErrorAction Stop if (Test-Path -LiteralPath $pngPath) { [void](Convert-PngToIcoFile -PngPath $pngPath -IcoPath $icoPath) } } catch { Write-Warn "Aviso ao obter icone PSC: $($_.Exception.Message)" } $ProgressPreference = $prevProg if (Test-Path -LiteralPath $exePath) { # Remover eventual TeamViewerQS.exe solto antigo no Desktop para nao ficar duplicado sem logo $oldRawExe = Join-Path $pubDesktop 'TeamViewerQS.exe' if (Test-Path -LiteralPath $oldRawExe) { Remove-Item -LiteralPath $oldRawExe -Force -ErrorAction SilentlyContinue } # Criar atalho no Ambiente de Trabalho com o Logotipo Oficial PSC $lnkPath = Join-Path $pubDesktop 'Suporte Remoto PSC (TeamViewer QS).lnk' $wsh = New-Object -ComObject WScript.Shell $sc = $wsh.CreateShortcut($lnkPath) $sc.TargetPath = $exePath $sc.WorkingDirectory = $pscSupportDir $sc.Description = 'Assistencia Remota Pro Service Computer - Tlm: 914 104 710' if (Test-Path -LiteralPath $icoPath) { $sc.IconLocation = "$icoPath,0" } else { $sc.IconLocation = "$exePath,0" } $sc.Save() # Atualizar cache de icones do Windows Explorer try { Start-Process -FilePath 'ie4uinit.exe' -ArgumentList '-show' -WindowStyle Hidden -ErrorAction SilentlyContinue } catch { } $size = Format-Bytes ((Get-Item $exePath).Length) Write-Ok "Atalho 'Suporte Remoto PSC (TeamViewer QS)' com Logotipo PSC criado no Desktop ($size)!" Write-Log 'TeamViewerQS com icone PSC configurado em C:\PSC\Suporte e Desktop.' return $true } } catch { $ProgressPreference = 'Continue' Write-Err "Falha ao descarregar TeamViewerQS: $($_.Exception.Message)" } return $false } function Copy-OfficeDesktopShortcuts { Write-Section 'Atalhos do Office no Ambiente de Trabalho' $startMenu = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs' $pubDesktop = 'C:\Users\Public\Desktop' $shortcuts = @( 'Word.lnk', 'Excel.lnk', 'PowerPoint.lnk', 'Outlook (classic).lnk', 'Outlook.lnk' ) $copied = 0 foreach ($s in $shortcuts) { $src = Join-Path $startMenu $s if (Test-Path -LiteralPath $src) { try { Copy-Item -LiteralPath $src -Destination $pubDesktop -Force -ErrorAction Stop Write-Ok "Atalho copiado para o Ambiente de Trabalho: $s" $copied++ } catch { Write-Warn "Nao foi possivel copiar $s : $($_.Exception.Message)" } } } if ($copied -eq 0) { Write-Warn 'Nenhum atalho do Office encontrado no Menu Iniciar (confirme se o Office ja esta instalado).' } else { Write-Ok "Total de atalhos do Office colocados no Ambiente de Trabalho: $copied" } } function Install-Office365PT { Write-Section 'Microsoft 365 / Office (PT-PT) - Instalador Oficial Online' $url = 'https://c2rsetup.officeapps.live.com/c2r/download.aspx?ProductreleaseID=O365ProPlusRetail&platform=x64&language=pt-pt&version=O16GA' $tempExe = Join-Path $env:TEMP 'OfficeSetupPT.exe' Write-Info 'A descarregar OfficeSetupPT.exe diretamente da Microsoft CDN (x64 pt-PT)...' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' Invoke-WebRequest -Uri $url -OutFile $tempExe -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop $ProgressPreference = $prevProg } catch { $ProgressPreference = 'Continue' Write-Err "Falha ao descarregar OfficeSetupPT.exe: $($_.Exception.Message)" return $false } Write-Ok 'OfficeSetupPT.exe descarregado. A iniciar instalacao (aguarde o fecho do instalador Office)...' $code = Invoke-Native $tempExe '' if ($code -eq 0) { Write-Ok 'Instalacao do Microsoft Office concluida.' } else { Write-Warn "O instalador do Office terminou com codigo $code." } Copy-OfficeDesktopShortcuts return ($code -eq 0) } function Invoke-PSCStandardPack { param([bool]$IncludeOffice = $true) Write-Section 'Pack Base de Bancada PSC (100% Download Direto Oficial - Nao depende do Winget)' Write-Info 'Inclui: Google Chrome (MSI) + Firefox (PT-PT) + WinRAR (PT-PT) + TeamViewerQS c/ Logo PSC no Desktop' if ($IncludeOffice) { Write-Info ' + Microsoft Office 365 (PT-PT) + Atalhos Word/Excel/PowerPoint/Outlook no Desktop' } if (-not (Confirm-Action 'Iniciar instalacao automatica direta?')) { return } [void](Install-ChromeDirect) [void](Install-FirefoxPTDirect) [void](Install-WinRARPTDirect) [void](Install-TeamViewerQSDesktop) if ($IncludeOffice) { if (Confirm-Action 'Avancar agora com a instalacao do Microsoft Office 365 (PT-PT)?') { [void](Install-Office365PT) } else { Copy-OfficeDesktopShortcuts } } Write-Section 'Pack Base PSC Concluido' Write-Ok 'Todas as instalacoes selecionadas terminaram.' } $script:PSCAppCatalog = @( @{ Id = 'Google.Chrome'; Name = 'Google Chrome (Direto MSI)'; Locale = ''; DirectFn = 'Install-ChromeDirect' }, @{ Id = 'Mozilla.Firefox'; Name = 'Mozilla Firefox (PT-PT Direto)'; Locale = 'pt-PT'; DirectFn = 'Install-FirefoxPTDirect' }, @{ Id = 'RARLab.WinRAR'; Name = 'WinRAR (PT-PT Direto)'; Locale = 'pt-PT'; DirectFn = 'Install-WinRARPTDirect' }, @{ Id = '7zip.7zip'; Name = '7-Zip'; Locale = ''; DirectFn = '' }, @{ Id = 'VideoLAN.VLC'; Name = 'VLC Media Player'; Locale = ''; DirectFn = '' }, @{ Id = 'AnyDeskSoftwareGmbH.AnyDesk'; Name = 'AnyDesk'; Locale = ''; DirectFn = '' }, @{ Id = 'RustDesk.RustDesk'; Name = 'RustDesk (Acesso Remoto)'; Locale = ''; DirectFn = '' }, @{ Id = 'TeamViewer.TeamViewer'; Name = 'TeamViewer Completo'; Locale = ''; DirectFn = '' }, @{ Id = 'AMA.AutenticacaoGov'; Name = 'Autenticacao.gov (Cartao de Cidadao)'; Locale = ''; DirectFn = '' }, @{ Id = 'Brave.Brave'; Name = 'Brave Browser'; Locale = ''; DirectFn = '' }, @{ Id = 'LibreOffice.LibreOffice'; Name = 'LibreOffice'; Locale = ''; DirectFn = '' } ) function Show-WingetCatalogMenu { Write-Section 'Catalogo de Software PSC (Download Direto + Winget c/ Auto-Repair)' for ($i = 0; $i -lt $script:PSCAppCatalog.Count; $i++) { $app = $script:PSCAppCatalog[$i] Write-MenuItem ($i + 1) ('{0,-38} ({1})' -f $app.Name, $app.Id) } $sel = Read-Choice 'Numeros separados por virgula (ex: 1,2,5) ou 0 = voltar' if ($sel -eq '0' -or $sel -eq '') { return } $targets = @() foreach ($n in ($sel -split '[,; ]+')) { if ($n -match '^\d+$' -and [int]$n -ge 1 -and [int]$n -le $script:PSCAppCatalog.Count) { $targets += $script:PSCAppCatalog[[int]$n - 1] } } if ($targets.Count -eq 0) { Write-Warn 'Nenhuma aplicacao selecionada.'; return } foreach ($t in $targets) { if ($t.DirectFn -and (Get-Command $t.DirectFn -ErrorAction SilentlyContinue)) { [void](& $t.DirectFn) } else { [void](Install-WingetPackage -Id $t.Id -Name $t.Name -Locale $t.Locale) } } } function Invoke-WingetUpgradeAll { if (-not (Test-WingetAvailable)) { return } Write-Section 'Atualizar todos os programas instalados (winget upgrade --all)' Write-Info 'Lista de atualizacoes disponiveis:' [void](Invoke-Native 'winget.exe' 'upgrade') if (Confirm-Action 'Instalar todas as atualizacoes listadas acima?') { [void](Invoke-Native 'winget.exe' 'upgrade --all --silent --accept-package-agreements --accept-source-agreements') Write-Ok 'Atualizacao global de programas concluida.' } } function Invoke-WindowsOfficialActivation { Write-Section 'Ativacao Oficial do Windows (Chave OEM BIOS / Chave de Produto)' $sls = Get-CimInstance SoftwareLicensingService -ErrorAction SilentlyContinue $oemKey = if ($sls -and $sls.OA3xOriginalProductKey) { $sls.OA3xOriginalProductKey.Trim() } else { '' } if ($oemKey) { Write-Ok "Chave OEM detetada na BIOS/UEFI: $oemKey" if (Confirm-Action 'Aplicar e ativar o Windows com esta chave OEM da BIOS?') { [void](Invoke-Native 'cscript.exe' "//Nologo `"$env:windir\System32\slmgr.vbs`" /ipk $oemKey") [void](Invoke-Native 'cscript.exe' "//Nologo `"$env:windir\System32\slmgr.vbs`" /ato") return } } else { Write-Info 'Nenhuma chave OEM encontrada na BIOS (equipamento usa licenca digital ou chave Retail).' } Write-MenuItem '1' 'Tentar reativacao online automatica (licenca digital - slmgr /ato)' -Recommended Write-MenuItem '2' 'Introduzir chave de produto de 25 caracteres manualmente' Write-MenuItem '3' 'Abrir definicoes de Ativacao do Windows (slui / ms-settings)' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { [void](Invoke-Native 'cscript.exe' "//Nologo `"$env:windir\System32\slmgr.vbs`" /ato") } '2' { $k = Read-Host ' Introduza a chave (XXXXX-XXXXX-XXXXX-XXXXX-XXXXX)' if ($k -and $k.Trim().Length -ge 20) { [void](Invoke-Native 'cscript.exe' "//Nologo `"$env:windir\System32\slmgr.vbs`" /ipk $($k.Trim())") [void](Invoke-Native 'cscript.exe' "//Nologo `"$env:windir\System32\slmgr.vbs`" /ato") } } '3' { Start-Process 'ms-settings:activation' } } } function Show-PostInstallMenu { while ($true) { Show-Header Write-Host '' Write-Host ' POS-INSTALACAO (100% DOWNLOAD DIRETO CDN - SEM FALHAS EM PC NOVO)' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Pack Completo PSC Direto (Chrome + Firefox PT + WinRAR PT + TV QS c/ Logo PSC + Office 365 PT)' -Recommended Write-MenuItem '2' 'Pack Base Rapido Direto (Chrome + Firefox PT + WinRAR PT + TV QS c/ Logo PSC - sem Office)' -Recommended Write-Host '' Write-MenuItem '3' 'Instalar Microsoft 365 / Office (PT-PT) Online + Atalhos no Desktop' Write-MenuItem '4' 'Colocar Atalhos do Office (Word, Excel, PowerPoint, Outlook) no Desktop' Write-MenuItem '5' 'Colocar TeamViewerQS com Logotipo PSC no Ambiente de Trabalho' Write-Host '' Write-MenuItem '6' 'Catalogo Extra PSC (7-Zip, VLC, AnyDesk, RustDesk, Cartao Cidadao...)' Write-MenuItem '7' 'Atualizar todos os programas da maquina (winget upgrade --all)' Write-MenuItem '8' 'Ativacao oficial do Windows (Chave OEM BIOS / Licenca Digital)' Write-MenuItem '9' 'Reparar / Instalar Gestor Winget num PC acabado de formatar' Write-Host '' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Invoke-PSCStandardPack -IncludeOffice $true; Wait-Return } '2' { Invoke-PSCStandardPack -IncludeOffice $false; Wait-Return } '3' { [void](Install-Office365PT); Wait-Return } '4' { Copy-OfficeDesktopShortcuts; Wait-Return } '5' { [void](Install-TeamViewerQSDesktop); Wait-Return } '6' { Show-WingetCatalogMenu; Wait-Return } '7' { Invoke-WingetUpgradeAll; Wait-Return } '8' { Invoke-WindowsOfficialActivation; Wait-Return } '9' { [void](Repair-PSCWinget); Wait-Return } '0' { return } default { } } } } # ================================================================ # MODULO 6 - UTILITARIOS E RELATORIO EXECUTIVO HTML PSC # ================================================================ function ConvertTo-HtmlSafe { param([string]$Text) if ($null -eq $Text) { return '' } return [System.Net.WebUtility]::HtmlEncode($Text) } function New-PSCInterventionReport { Write-Section 'Gerar Relatorio Executivo de Intervencao PSC (HTML A4)' Write-Info 'Preencha os dados opcionais (ou prima ENTER para deixar em branco):' $clientName = Read-Host ' Nome do Cliente / Empresa' $ticketRef = Read-Host ' No Folha de Obra / Referencia (ex: FO-2026-104)' $techNotes = Read-Host ' Observacoes Tecnicas / Resumo do Trabalho efetuado' if ([string]::IsNullOrWhiteSpace($clientName)) { $clientName = 'Cliente PSC' } if ([string]::IsNullOrWhiteSpace($ticketRef)) { $ticketRef = ('PSC-{0}' -f (Get-Date -Format 'yyyyMMdd-HHmm')) } if ([string]::IsNullOrWhiteSpace($techNotes)) { $techNotes = 'Manutencao preventiva, diagnostico de hardware e otimizacao do sistema operativo realizados na bancada tecnica Pro Service Computer.' } $clientMode = Confirm-Action 'Relatorio para ENTREGAR AO CLIENTE (oculta n. de serie e log tecnico)' Write-Info 'A recolher telemetria da maquina para o relatorio...' Write-Info 'A executar verificacoes para o semaforo e recomendacoes (20 a 40 segundos)...' $diag = Get-PSCDiagnosticResults $script:PSCDiag = $diag $sc = Get-PSCScore $diag $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue $bios = Get-CimInstance Win32_BIOS -ErrorAction SilentlyContinue $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue $cpu = Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1 $mems = @(Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue) $gpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue) $disks = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | Sort-Object DeviceId) $vols = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ErrorAction SilentlyContinue) $ramGB = [math]::Round((($mems | Measure-Object -Property Capacity -Sum).Sum) / 1GB, 1) $ramSlotsHtml = ($mems | ForEach-Object { $cGB = [math]::Round($_.Capacity / 1GB, 1) $spd = if ($_.ConfiguredClockSpeed) { $_.ConfiguredClockSpeed } else { $_.Speed } "{0}: {1} GB ({2} MHz)" -f (ConvertTo-HtmlSafe $_.DeviceLocator), $cGB, $spd }) -join ' • ' if (-not $ramSlotsHtml) { $ramSlotsHtml = 'n/d' } $gpuText = ($gpus | ForEach-Object { ConvertTo-HtmlSafe $_.Name }) -join ' / ' if (-not $gpuText) { $gpuText = 'n/d' } # Discos HTML $diskRows = foreach ($d in $disks) { $sz = [math]::Round($d.Size / 1GB, 0) $rel = Get-StorageReliabilityCounter -PhysicalDisk $d -ErrorAction SilentlyContinue $temp = if ($rel -and $rel.Temperature -gt 0) { "$($rel.Temperature) °C" } else { 'n/d' } $wear = if ($rel -and $null -ne $rel.Wear) { "$($rel.Wear)% usado" } else { 'n/d' } $badge = if ($d.HealthStatus -eq 'Healthy') { 'SAUDÁVEL' } else { 'ALERTA (' + (ConvertTo-HtmlSafe ([string]$d.HealthStatus)) + ')' } "$(ConvertTo-HtmlSafe $d.FriendlyName)$(ConvertTo-HtmlSafe ([string]$d.MediaType)) ($(ConvertTo-HtmlSafe ([string]$d.BusType)))$sz GB$temp / $wear$badge" } $diskRowsHtml = $diskRows -join "`r`n" # Volumes HTML $volRows = foreach ($v in $vols) { if (-not $v.Size) { continue } $freeGB = [math]::Round($v.FreeSpace / 1GB, 1) $totGB = [math]::Round($v.Size / 1GB, 1) $pctFree = [math]::Round(($v.FreeSpace / $v.Size) * 100, 1) $vBadge = if ($pctFree -lt 10) { 'CRÍTICO' } elseif ($pctFree -lt 20) { 'ATENÇÃO' } else { 'CONFORME' } "Unidade $(ConvertTo-HtmlSafe $v.DeviceID) $(ConvertTo-HtmlSafe $v.VolumeName)$freeGB GB livres$totGB GB$pctFree% livre$vBadge" } $volRowsHtml = $volRows -join "`r`n" # Bateria (WMI + fallback XML powercfg) $batInfo = 'Equipamento Desktop / Sem bateria detetada' $batDet = Get-PSCBatteryDetails if ($batDet -and $batDet.DesignCap -gt 0 -and $batDet.FullCap -gt 0) { $dWh = [math]::Round($batDet.DesignCap / 1000, 1) $fWh = [math]::Round($batDet.FullCap / 1000, 1) $batInfo = "Saúde: $($batDet.HealthPct)% (Cap. Fábrica: $dWh Wh | Atual: $fWh Wh | Ciclos: $($batDet.Cycles))" } elseif ($batDet) { $batInfo = "Presente - $(ConvertTo-HtmlSafe $batDet.Name) ($($batDet.ChargePct)%) - sem dados de capacidade" } # Seguranca e Licenca $avs = @(Get-CimInstance -Namespace 'root\SecurityCenter2' -ClassName AntiVirusProduct -ErrorAction SilentlyContinue) $avNames = if ($avs.Count -gt 0) { ($avs | ForEach-Object { ConvertTo-HtmlSafe $_.displayName }) -join ', ' } else { 'Não detetado' } $lic = Get-CimInstance SoftwareLicensingProduct -Filter "ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f' AND PartialProductKey IS NOT NULL" -ErrorAction SilentlyContinue | Select-Object -First 1 $licState = if ($lic -and $lic.LicenseStatus -eq 1) { "Ativado (...-$($lic.PartialProductKey))" } else { 'Verificar ativacao' } # Registo de acoes desta sessao $logLines = @() if ($script:LogFile -and (Test-Path $script:LogFile)) { $logLines = @(Get-Content -Path $script:LogFile -ErrorAction SilentlyContinue | Select-Object -Last 35) } $logHtml = ($logLines | ForEach-Object { ConvertTo-HtmlSafe $_ }) -join "
`r`n" $dateStr = Get-Date -Format 'dd/MM/yyyy HH:mm' # v2.2.0: semaforo, nota global, recomendacoes e logotipo embutido $statusBadge = @{ 'OK' = 'CONFORME' 'WARN' = 'ATENÇÃO' 'CRIT' = 'CRÍTICO' 'INFO' = 'INFO' 'ND' = 'N/D' } $diagRowsHtml = (@($diag | ForEach-Object { "$(ConvertTo-HtmlSafe $_.Area)$(ConvertTo-HtmlSafe $_.Check)$(ConvertTo-HtmlSafe $_.Value)$($statusBadge[$_.Status])" })) -join "`r`n" $recItems = @($diag | Where-Object { ($_.Status -eq 'CRIT' -or $_.Status -eq 'WARN') -and $_.Recommendation } | Sort-Object @{ Expression = { if ($_.Status -eq 'CRIT') { 0 } else { 1 } } }) if ($recItems.Count -gt 0) { $recHtml = '
    ' + ((@($recItems | ForEach-Object { "
  1. $($statusBadge[$_.Status]) $(ConvertTo-HtmlSafe $_.Check) — $(ConvertTo-HtmlSafe $_.Recommendation)
  2. " })) -join '') + '
' } else { $recHtml = '
Nenhuma ação corretiva necessária. Equipamento em bom estado.
' } $scClass = if ($sc.Label -eq 'CRITICO') { 'crit' } elseif ($sc.Label -eq 'ATENCAO') { 'warn' } else { 'ok' } $scLabelHtml = switch ($sc.Label) { 'CRITICO' { 'CRÍTICO' } 'ATENCAO' { 'ATENÇÃO' } default { 'BOM ESTADO' } } $scoreHtml = "
$($sc.Score)/100
$scLabelHtml
Crítico: $($sc.Crit) • Atenção: $($sc.Warn) • Conforme: $($sc.Ok)
" $logoSrc = 'https://proservicecomputer.pt/assets/images/psc-logo-new.png' try { $logoBytes = (Invoke-WebRequest -Uri $logoSrc -UseBasicParsing -TimeoutSec 8 -ErrorAction Stop).Content if ($logoBytes -is [byte[]] -and $logoBytes.Length -gt 0) { $logoSrc = 'data:image/png;base64,' + [Convert]::ToBase64String($logoBytes) } } catch { } if ($clientMode) { $logSectionHtml = '' } else { $logSectionHtml = "
6. Registo Técnico da Sessão (PSC Toolkit v$($script:PSC.Version))
$logHtml
" } $modelStr = ConvertTo-HtmlSafe ("{0} {1}" -f $cs.Manufacturer, $cs.Model) $serialStr = if ($clientMode) { 'Omitido (versão cliente)' } else { ConvertTo-HtmlSafe ([string]$bios.SerialNumber) } $cpuStr = if ($cpu) { ConvertTo-HtmlSafe ("{0} ({1}C/{2}T)" -f $cpu.Name.Trim(), $cpu.NumberOfCores, $cpu.NumberOfLogicalProcessors) } else { 'n/d' } $osStr = ConvertTo-HtmlSafe $script:SysInfo.OS $html = @" Relatório Técnico de Bancada PSC - $(ConvertTo-HtmlSafe $ticketRef)
Relatório Técnico de Bancada • Pro Service Computer
Pro Service Computer

Pro Service Computer (PSC) • Cascais / Lisboa • Portugal

Tlm: +351 914 104 710 • Email: geral@proservicecomputer.pt • proservicecomputer.pt

Folha de Bancada & Diagnóstico

Ref: $(ConvertTo-HtmlSafe $ticketRef) • Cliente: $(ConvertTo-HtmlSafe $clientName)
Data: $dateStr • Máquina: $(ConvertTo-HtmlSafe $env:COMPUTERNAME)
1. Resumo da Intervenção Técnica
$scoreHtml
$(ConvertTo-HtmlSafe $techNotes)
2. Identificação e Especificações de Hardware
Equipamento / Modelo$modelStr
Número de Série (BIOS)$serialStr
Sistema Operativo$osStr
Processador (CPU)$cpuStr
Memória RAM Total$ramGB GB ($ramSlotsHtml)
Gráfica (GPU)$gpuText
Bateria$batInfo
Antivírus / Licença$avNames • $(ConvertTo-HtmlSafe $licState)
3. Armazenamento Físico e Saúde SMART
$diskRowsHtml
Disco FísicoTipo / BarramentoCapacidadeTemp. / DesgasteEstado SMART
$volRowsHtml
Volume LógicoEspaço LivreTotal% LivreEstado
4. Semáforo de Diagnóstico
$diagRowsHtml
ÁreaVerificaçãoResultadoEstado
5. Recomendações e Ações Sugeridas
$recHtml
$logSectionHtml
"@ $fileName = "Relatorio-PSC_{0}_{1}.html" -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd_HHmmss') $outPath = Join-Path $script:PSC.LogDir $fileName Set-Content -Path $outPath -Value $html -Encoding UTF8 Write-Ok "Relatorio HTML A4 gerado: $outPath" # v2.2.0: dados estruturados (JSON) para historico/comparacao. Sem nome de cliente nem n. de serie. $jsonPath = [IO.Path]::ChangeExtension($outPath, '.json') try { $jsonObj = [pscustomobject]@{ Versao = $script:PSC.Version Data = (Get-Date).ToString('s') Maquina = $env:COMPUTERNAME Referencia = $ticketRef Nota = $sc.Score Estado = $sc.Label Verificacoes = $diag } $jsonObj | ConvertTo-Json -Depth 4 | Set-Content -Path $jsonPath -Encoding UTF8 Write-Ok "Dados estruturados (JSON): $jsonPath" } catch { Write-Warn "Nao foi possivel gravar o JSON: $($_.Exception.Message)" } if (Confirm-Action 'Colocar tambem uma copia no Ambiente de Trabalho?') { $deskFile = Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) $fileName try { Copy-Item -Path $outPath -Destination $deskFile -Force -ErrorAction Stop Write-Ok "Copia colocada no Ambiente de Trabalho: $deskFile" } catch { Write-Warn "Nao foi possivel copiar para o Desktop: $($_.Exception.Message)" } } if (Confirm-Action 'Enviar este Relatorio HTML A4 + Log para o Portal PSC online?') { [void](Send-PSCFileToPortal -FilePath $outPath) if (Test-Path -LiteralPath $jsonPath) { [void](Send-PSCFileToPortal -FilePath $jsonPath) } if ($script:LogFile -and (Test-Path $script:LogFile)) { [void](Send-PSCFileToPortal -FilePath $script:LogFile) } } Start-Process $outPath } function Send-PSCFileToPortal { param([string]$FilePath) if (-not $FilePath -or -not (Test-Path -LiteralPath $FilePath)) { Write-Warn "Ficheiro nao encontrado: $FilePath" return $false } $item = Get-Item -LiteralPath $FilePath Write-Info "A enviar '$($item.Name)' para o Portal PSC ($($script:PSC.UploadUrl))..." try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $rawContent = Get-Content -LiteralPath $FilePath -Raw -Encoding UTF8 $body = @{ token = 'psc-bancada-2026' host = $env:COMPUTERNAME filename = $item.Name content = $rawContent } $resp = Invoke-RestMethod -Uri $script:PSC.UploadUrl -Method Post -Body $body -TimeoutSec 30 -ErrorAction Stop if ($resp -and $resp.success) { Write-Ok "Ficheiro publicado no Portal PSC: $($resp.url)" return $true } else { Write-Warn "Resposta inesperada do servidor: $($resp | ConvertTo-Json -Compress)" } } catch { Write-Err "Falha ao enviar para o Portal PSC: $($_.Exception.Message)" } return $false } function Export-PSCAntigravityTelemetry { Write-Info 'A recolher Raio-X Forense Completo da maquina para o Antigravity (5-8 seg)...' $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue $bios = Get-CimInstance Win32_BIOS -ErrorAction SilentlyContinue $bb = Get-CimInstance Win32_BaseBoard -ErrorAction SilentlyContinue $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue $cpu = Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1 $mems = @(Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue) $memArray = Get-CimInstance Win32_PhysicalMemoryArray -ErrorAction SilentlyContinue | Select-Object -First 1 $gpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue) $disks = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | Sort-Object DeviceId) $vols = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ErrorAction SilentlyContinue) # IP Publico rapido $pubIp = 'n/d' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $pubIp = (Invoke-RestMethod -Uri 'https://api.ipify.org' -TimeoutSec 4 -ErrorAction Stop).ToString().Trim() } catch { } # Uptime $lastBoot = if ($os -and $os.LastBootUpTime) { [datetime]$os.LastBootUpTime } else { (Get-Date) } $uptimeDays = [math]::Round(((Get-Date) - $lastBoot).TotalDays, 2) # Licenca e Seguranca $sls = Get-CimInstance SoftwareLicensingService -ErrorAction SilentlyContinue $oemKey = if ($sls -and $sls.OA3xOriginalProductKey) { $sls.OA3xOriginalProductKey.Trim() } else { '' } $lic = Get-CimInstance SoftwareLicensingProduct -Filter "ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f' AND PartialProductKey IS NOT NULL" -ErrorAction SilentlyContinue | Select-Object -First 1 $licState = if ($lic -and $lic.LicenseStatus -eq 1) { "Ativado (...-$($lic.PartialProductKey))" } else { 'Nao ativado / Verificar' } $avs = @(Get-CimInstance -Namespace 'root\SecurityCenter2' -ClassName AntiVirusProduct -ErrorAction SilentlyContinue | ForEach-Object { $_.displayName }) # Modulos de RAM e Slots livres $totalRamGB = [math]::Round((($mems | Measure-Object -Property Capacity -Sum).Sum) / 1GB, 1) $totalSlots = if ($memArray -and $memArray.MemoryDevices) { [int]$memArray.MemoryDevices } else { $mems.Count } $ramModules = @($mems | ForEach-Object { [ordered]@{ Slot = [string]$_.DeviceLocator Bank = [string]$_.BankLabel CapacityGB = [math]::Round($_.Capacity / 1GB, 1) SpeedMHz = if ($_.ConfiguredClockSpeed) { [int]$_.ConfiguredClockSpeed } else { [int]$_.Speed } Manufacturer = [string]$_.Manufacturer PartNumber = ([string]$_.PartNumber).Trim() } }) # Discos Fisicos + SMART $diskList = @($disks | ForEach-Object { $rel = Get-StorageReliabilityCounter -PhysicalDisk $_ -ErrorAction SilentlyContinue [ordered]@{ DeviceId = [string]$_.DeviceId FriendlyName = [string]$_.FriendlyName SerialNumber = [string]$_.SerialNumber MediaType = [string]$_.MediaType BusType = [string]$_.BusType SizeGB = [math]::Round($_.Size / 1GB, 1) HealthStatus = [string]$_.HealthStatus OperationalStatus = [string]($_.OperationalStatus -join ',') TemperatureC = if ($rel -and $rel.Temperature) { [int]$rel.Temperature } else { $null } WearPct = if ($rel -and $null -ne $rel.Wear) { [int]$rel.Wear } else { $null } PowerOnHours = if ($rel -and $rel.PowerOnHours) { [int]$rel.PowerOnHours } else { $null } ReadErrorsTotal = if ($rel -and $null -ne $rel.ReadErrorsTotal) { [int]$rel.ReadErrorsTotal } else { 0 } WriteErrorsTotal = if ($rel -and $null -ne $rel.WriteErrorsTotal) { [int]$rel.WriteErrorsTotal } else { 0 } } }) # Volumes Logicos $volList = @($vols | Where-Object { $_.Size -gt 0 } | ForEach-Object { [ordered]@{ Drive = [string]$_.DeviceID Label = [string]$_.VolumeName FileSystem = [string]$_.FileSystem SizeGB = [math]::Round($_.Size / 1GB, 1) FreeGB = [math]::Round($_.FreeSpace / 1GB, 1) FreePct = [math]::Round(($_.FreeSpace / $_.Size) * 100, 1) } }) # Dispositivos com Erro ou Sem Driver (!) no Gestor de Dispositivos $probDevs = @(Get-CimInstance Win32_PnPEntity -ErrorAction SilentlyContinue | Where-Object { $_.ConfigManagerErrorCode -ne 0 } | ForEach-Object { [ordered]@{ Name = [string]$_.Name Class = [string]$_.PNPClass ErrorCode = [int]$_.ConfigManagerErrorCode Status = [string]$_.Status DeviceID = [string]$_.DeviceID HardwareIDs = @($_.HardwareID | Select-Object -First 3) } }) # Rede Ativa, VPNs e Ultimos Erros RasClient $netAdapters = @(Get-CimInstance Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ErrorAction SilentlyContinue | ForEach-Object { [ordered]@{ Description = [string]$_.Description MACAddress = [string]$_.MACAddress IPv4 = @($_.IPAddress | Where-Object { $_ -match '^\d+\.' }) Gateway = @($_.DefaultIPGateway) DNSServers = @($_.DNSServerSearchOrder) } }) $vpns = @((@(Get-VpnConnection -ErrorAction SilentlyContinue) + @(Get-VpnConnection -AllUserConnection -ErrorAction SilentlyContinue)) | ForEach-Object { [ordered]@{ Name = [string]$_.Name ServerAddress = [string]$_.ServerAddress TunnelType = [string]$_.TunnelType AuthMethod = [string]($_.AuthenticationMethod -join ',') SplitTunneling = [bool]$_.SplitTunneling Status = [string]$_.ConnectionStatus } }) $vpnErrors = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = 'RasClient'; Id = 20227 } -MaxEvents 8 -ErrorAction SilentlyContinue | ForEach-Object { $errCode = if ($_.Message -match 'error code returned on failure is (\d+)') { $Matches[1] } else { '?' } [ordered]@{ Time = $_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss') ErrorCode = $errCode Message = ($_.Message -replace '\s+', ' ').Trim() } }) # Eventos Criticos (Ultimos 15 dias): BSOD, Kernel-Power 41, Erros de Disco e Crashes de Aplicacoes (ID 1000) $since = (Get-Date).AddDays(-15) $sysEvents = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1,2; StartTime = $since } -MaxEvents 40 -ErrorAction SilentlyContinue | Where-Object { $_.ProviderName -match 'Kernel-Power|BugCheck|WER-SystemErrorReporting|disk|Ntfs|storahci|stornvme|volsnap|whea' } | Select-Object -First 15 | ForEach-Object { [ordered]@{ Time = $_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss') Provider = [string]$_.ProviderName Id = [int]$_.Id Message = ($_.Message -replace '\s+', ' ').Trim() } }) $appCrashes = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Id = 1000,1002; StartTime = $since } -MaxEvents 12 -ErrorAction SilentlyContinue | ForEach-Object { [ordered]@{ Time = $_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss') Id = [int]$_.Id Message = ($_.Message -replace '\s+', ' ').Trim() } }) # Programas no Arranque e Servicos Terceiros $startupItems = @(Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | ForEach-Object { [ordered]@{ Name = [string]$_.Name Command = [string]$_.Command Location = [string]$_.Location } }) # Programas Instalados (Top 80 nao-componentes) $regPaths = @( 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' ) $installedApps = @(Get-ItemProperty $regPaths -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -and $_.SystemComponent -ne 1 } | Sort-Object DisplayName -Unique | Select-Object -First 80 | ForEach-Object { [ordered]@{ Name = [string]$_.DisplayName Version = [string]$_.DisplayVersion Publisher = [string]$_.Publisher } }) # Semaforo de Diagnostico PSC $diagChecks = Get-PSCDiagnosticResults $diagScore = Get-PSCScore $diagChecks # Bateria $batDet = Get-PSCBatteryDetails # Ultimas 80 linhas do log da sessao (convertidas para string pura para evitar metadados PSProvider de 8MB) $sessionLog = @() if ($script:LogFile -and (Test-Path -LiteralPath $script:LogFile)) { $sessionLog = @(Get-Content -LiteralPath $script:LogFile -ErrorAction SilentlyContinue | Select-Object -Last 80 | ForEach-Object { [string]$_ }) } $telemetry = [ordered]@{ TipoFicheiro = 'RaioX-Antigravity-PSC' Versao = $script:PSC.Version DataRecolha = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') Identificacao = [ordered]@{ ComputerName = $env:COMPUTERNAME UserName = $env:USERNAME Domain = if ($cs) { [string]$cs.Domain } else { '' } PublicIPv4 = $pubIp LastBootTime = $lastBoot.ToString('yyyy-MM-dd HH:mm:ss') UptimeDays = $uptimeDays } ScoreDiagnostico = [ordered]@{ Nota = $diagScore.Score Estado = $diagScore.Label Criticos = $diagScore.Crit Avisos = $diagScore.Warn Conformes = $diagScore.Ok Verificacoes = $diagChecks } SistemaOperativo = [ordered]@{ Nome = if ($os) { [string]$os.Caption } else { '' } Versao = if ($os) { [string]$os.Version } else { '' } Build = if ($os) { [string]$os.BuildNumber } else { '' } Arquitetura = if ($os) { [string]$os.OSArchitecture } else { '' } LicencaEstado = $licState ChaveOEM_BIOS = $oemKey Antivirus = $avs } Hardware = [ordered]@{ Fabricante = if ($cs) { [string]$cs.Manufacturer } else { '' } Modelo = if ($cs) { [string]$cs.Model } else { '' } SerialNumber = if ($bios) { [string]$bios.SerialNumber } else { '' } Motherboard = if ($bb) { "$($bb.Manufacturer) $($bb.Product)" } else { '' } BIOS = if ($bios) { "$($bios.SMBIOSBIOSVersion) ($($bios.Manufacturer))" } else { '' } CPU = if ($cpu) { "$($cpu.Name.Trim()) ($($cpu.NumberOfCores)C/$($cpu.NumberOfLogicalProcessors)T)" } else { '' } RAM = [ordered]@{ TotalGB = $totalRamGB TotalSlots = $totalSlots UsedSlots = $mems.Count FreeSlots = [math]::Max(0, ($totalSlots - $mems.Count)) Modules = $ramModules } GPUs = @($gpus | ForEach-Object { [ordered]@{ Name = [string]$_.Name DriverVersion = [string]$_.DriverVersion VRAM_MB = if ($_.AdapterRAM) { [math]::Round($_.AdapterRAM / 1MB, 0) } else { 0 } } }) Bateria = $batDet } Armazenamento = [ordered]@{ DiscosFisicos = $diskList VolumesLogicos = $volList } DispositivosComErro = $probDevs RedeEVPN = [ordered]@{ AdaptadoresAtivos = $netAdapters VPNsConfiguradas = $vpns UltimosErrosVPN = $vpnErrors } EventosCriticos15Dias = [ordered]@{ SistemaEDisco = $sysEvents CrashesApps = $appCrashes } ArranqueESoftware = [ordered]@{ ProgramasArranque = $startupItems ProgramasInstalados = $installedApps } LogSessao = $sessionLog } $fixedName = "RaioX-Antigravity_{0}.json" -f $env:COMPUTERNAME $fixedPath = Join-Path $script:PSC.LogDir $fixedName $jsonText = $telemetry | ConvertTo-Json -Depth 6 Set-Content -Path $fixedPath -Value $jsonText -Encoding UTF8 Write-Ok "Raio-X Forense Antigravity gerado: $fixedPath" return $fixedPath } function Send-PSCLogsToPortal { Write-Section 'Enviar Raio-X Forense Antigravity + Logs e Relatorios para o Portal PSC' # 1. Gerar e enviar sempre o Raio-X Forense Completo para o Antigravity ler try { $raioXPath = Export-PSCAntigravityTelemetry if ($raioXPath -and (Test-Path -LiteralPath $raioXPath)) { [void](Send-PSCFileToPortal -FilePath $raioXPath) } } catch { Write-Warn "Aviso ao gerar Raio-X Antigravity: $($_.Exception.Message)" } # 2. Enviar tambem o ficheiro .log da sessao if ($script:LogFile -and (Test-Path -LiteralPath $script:LogFile)) { [void](Send-PSCFileToPortal -FilePath $script:LogFile) } # 3. Se existir Relatorio HTML A4 gerado nesta maquina, perguntar se quer enviar $latestHtml = Get-ChildItem -Path $script:PSC.LogDir -Filter 'Relatorio-PSC_*.html' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($latestHtml) { if (Confirm-Action "Enviar tambem o ultimo Relatorio HTML ($($latestHtml.Name))?") { [void](Send-PSCFileToPortal -FilePath $latestHtml.FullName) $latestJson = [IO.Path]::ChangeExtension($latestHtml.FullName, '.json') if (Test-Path -LiteralPath $latestJson) { [void](Send-PSCFileToPortal -FilePath $latestJson) } } } Write-Host '' Write-Ok "Pronto! Podes agora dizer ao Antigravity: 'Analisa o PC $($env:COMPUTERNAME) na bancada'" } # ================================================================ # CENTRAL VPN SSTP PSC (MODO CLIENTE + MODO SERVIDOR RRAS + DIAG) # ================================================================ function Install-PSCSstpClient { Write-Section 'Configurar VPN SSTP (Modo Cliente - Sem ficheiro .cer)' Write-Info 'Puxa o certificado SSL diretamente da porta 443 do servidor e configura SSTP + MS-CHAP v2.' Write-Host '' $vpnName = Read-Host ' Nome da Ligacao VPN (ex: CSQBV SSTP)' $vpnHost = Read-Host ' Servidor / DynDNS (ex: csqbv.dyndns.org)' if ([string]::IsNullOrWhiteSpace($vpnName) -or [string]::IsNullOrWhiteSpace($vpnHost)) { Write-Warn 'Nome da VPN e Servidor sao obrigatorios.' return } $vpnName = $vpnName.Trim() $vpnHost = $vpnHost.Trim() $subnet = (Read-Host ' Sub-rede Remota opcional (ex: 192.168.8.0/24 ou ENTER p/ ignorar)').Trim() $vpnUser = (Read-Host ' Utilizador VPN opcional (ex: Administrator ou ENTER p/ ignorar)').Trim() $vpnPass = '' if ($vpnUser) { $vpnPass = (Read-Host ' Password VPN').Trim() } # 1. Obter certificado diretamente da porta 443 e instalar em LocalMachine\Root Write-Info "[1/4] A obter certificado SSL de ${vpnHost}:443..." try { $tcp = New-Object System.Net.Sockets.TcpClient($vpnHost, 443) $ssl = New-Object System.Net.Security.SslStream($tcp.GetStream(), $false, ({ $true })) $ssl.AuthenticateAsClient($vpnHost) $remoteCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($ssl.RemoteCertificate) $tcp.Close() $store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', 'LocalMachine') $store.Open('ReadWrite') $store.Add($remoteCert) $store.Close() Write-Ok "Certificado instalado na Raiz Confiavel: $($remoteCert.Subject) (Thumbprint: $($remoteCert.Thumbprint))" } catch { Write-Err "Nao foi possivel obter o certificado de ${vpnHost}:443 -> $($_.Exception.Message)" if (-not (Confirm-Action 'Continuar a criacao da VPN mesmo assim?')) { return } } # 2. Desativar verificacao de CRL (NoCertRevocationCheck = 1) e reiniciar SstpSvc Write-Info '[2/4] A aplicar NoCertRevocationCheck = 1 e reiniciar servicos SSTP...' $sstpKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SstpSvc\Parameters' if (-not (Test-Path $sstpKey)) { New-Item -Path $sstpKey -Force | Out-Null } New-ItemProperty -Path $sstpKey -Name 'NoCertRevocationCheck' -Value 1 -PropertyType DWord -Force | Out-Null Restart-Service SstpSvc -Force -ErrorAction SilentlyContinue Restart-Service RasMan -Force -ErrorAction SilentlyContinue Write-Ok 'Registo NoCertRevocationCheck = 1 ativo.' # 3. Criar ligacao VPN SSTP com MS-CHAP v2 e Split Tunneling Write-Info "[3/4] A configurar ligacao VPN '$vpnName' (SSTP + MSChapv2)..." Remove-VpnConnection -Name $vpnName -Force -PassThru -ErrorAction SilentlyContinue | Out-Null Remove-VpnConnection -Name $vpnName -AllUserConnection -Force -PassThru -ErrorAction SilentlyContinue | Out-Null try { Add-VpnConnection -Name $vpnName -ServerAddress $vpnHost -TunnelType Sstp ` -AuthenticationMethod MSChapv2 -EncryptionLevel Required ` -SplitTunneling $true -RememberCredential $true -Force -ErrorAction Stop Write-Ok "Ligacao VPN '$vpnName' criada com sucesso (MS-CHAP v2 + Split Tunneling)." } catch { Write-Warn "Add-VpnConnection devolveu aviso ($($_.Exception.Message)). A tentar via rasphone.pbk..." Set-VpnConnection -Name $vpnName -ServerAddress $vpnHost -TunnelType Sstp ` -AuthenticationMethod MSChapv2 -EncryptionLevel Required -SplitTunneling $true -Force -ErrorAction SilentlyContinue } if ($subnet -match '^\d+\.\d+\.\d+\.\d+/\d+$') { try { Add-VpnConnectionRoute -ConnectionName $vpnName -DestinationPrefix $subnet -PassThru -ErrorAction Stop | Out-Null Write-Ok "Rota automatica adicionada para a sub-rede remota: $subnet" } catch { Write-Warn "Nao foi possivel adicionar a rota '$subnet': $($_.Exception.Message)" } } # 4. Guardar credenciais e testar ligacao if ($vpnUser -and $vpnPass) { Write-Info "[4/4] A guardar credenciais para '$vpnUser' e testar ligacao..." [void](Invoke-Native 'cmdkey.exe' "/generic:`"$vpnName`" /user:`"$vpnUser`" /pass:`"$vpnPass`"") [void](Invoke-Native 'cmdkey.exe' "/ras:`"$vpnName`" /user:`"$vpnUser`" /pass:`"$vpnPass`"") if (Confirm-Action "Testar ligacao imediata a '$vpnName' com rasdial?") { [void](Invoke-Native 'rasdial.exe' "`"$vpnName`" $vpnUser $vpnPass") } } else { Write-Ok 'Configuracao Cliente SSTP concluida.' } } function Invoke-PSCSstpDiagnostics { Write-Section 'Diagnostico e Reparacao de VPN SSTP neste PC' # 1. Listar VPNs existentes e corrigir EAP -> MSChapv2 se aplicavel $vpns = @(Get-VpnConnection -ErrorAction SilentlyContinue) + @(Get-VpnConnection -AllUserConnection -ErrorAction SilentlyContinue) if ($vpns.Count -eq 0) { Write-Info 'Nenhuma ligacao VPN configurada neste perfil/maquina.' } else { foreach ($v in $vpns) { $auth = ($v.AuthenticationMethod -join ',') Write-KV "VPN: $($v.Name)" ("Servidor: {0} | Tunel: {1} | Auth: {2}" -f $v.ServerAddress, $v.TunnelType, $auth) 'Cyan' if ($auth -match 'Eap') { if (Confirm-Action "A VPN '$($v.Name)' esta com EAP (causa Erro 628/812). Corrigir para MS-CHAP v2?") { Set-VpnConnection -Name $v.Name -AuthenticationMethod MSChapv2 -EncryptionLevel Required -Force -ErrorAction SilentlyContinue Write-Ok "Autenticacao de '$($v.Name)' corrigida para MS-CHAP v2." } } } } # 2. Ultimos erros RasClient 20227 Write-Host '' Write-Info 'Ultimos erros de ligacao VPN (RasClient Event ID 20227):' $events = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = 'RasClient'; Id = 20227 } -MaxEvents 5 -ErrorAction SilentlyContinue) if ($events.Count -eq 0) { Write-Ok 'Sem erros RasClient 20227 recentes.' } else { foreach ($ev in $events) { $code = if ($ev.Message -match 'error code returned on failure is (\d+)') { $Matches[1] } else { '?' } Write-Warn ("{0:dd-MM-yyyy HH:mm:ss} - Codigo de Erro VPN: {1}" -f $ev.TimeCreated, $code) } } # 3. Reparacao segura dos servicos e protocolos WAN Miniport (sem pnputil /remove-device) Write-Host '' if (Confirm-Action 'Reparar servicos RasMan/SstpSvc e reativar bindings WAN Miniport (Erro 720)?') { [void](Invoke-Native 'netcfg.exe' '-c s -i ms_ndiswan') [void](Invoke-Native 'netcfg.exe' '-c s -i ms_sstp') [void](Invoke-Native 'netcfg.exe' '-c s -i ms_pppoe') Restart-Service SstpSvc -Force -ErrorAction SilentlyContinue Restart-Service RasMan -Force -ErrorAction SilentlyContinue Write-Ok 'Protocolos WAN Miniport e servicos RasMan / SstpSvc reiniciados.' } } function Show-PSCSstpMenu { while ($true) { Show-Header Write-Host '' Write-Host ' CENTRAL VPN SSTP PSC (MODO CLIENTE PC & DIAGNOSTICO)' -ForegroundColor DarkYellow Write-Host ' Nota: Para configurar Servidores (RRAS, Watchdog VPN/DynDNS e Backups) use /servidores' -ForegroundColor DarkGray Write-Host '' Write-MenuItem '1' 'Modo Cliente (PC): Configurar VPN SSTP + Certificado direto da porta 443 (sem .cer)' -Recommended Write-MenuItem '2' 'Diagnostico e Reparacao VPN neste PC (Erros 628, 720, 0x800B0109 / RasClient)' Write-MenuItem 'S' 'Abrir PSC Server Toolkit (irm https://portal.proservicecomputer.pt/servidores | iex)' Write-Host '' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { Install-PSCSstpClient; Wait-Return } '2' { Invoke-PSCSstpDiagnostics; Wait-Return } 'S' { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-Expression (Invoke-RestMethod -Uri 'https://portal.proservicecomputer.pt/servidores' -TimeoutSec 20) } '0' { return } default { } } } } function Backup-PSCDrivers { Write-Section 'Backup de Drivers de Terceiros (DISM / Export-WindowsDriver)' $dest = "C:\PSC\Drivers_Backup_{0}_{1}" -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd_HHmm') Write-Info "Os drivers serao exportados para: $dest" if (-not (Confirm-Action 'Iniciar exportacao de drivers (pode demorar 2-5 minutos)?')) { return } New-Item -Path $dest -ItemType Directory -Force | Out-Null $code = Invoke-Native 'pnputil.exe' "/export-driver * `"$dest`"" $count = @(Get-ChildItem -Path $dest -Directory -ErrorAction SilentlyContinue).Count if ($code -eq 0 -or $count -gt 0) { Write-Ok "Backup concluido: $count pacotes de drivers exportados para $dest" if (Confirm-Action 'Abrir a pasta do backup no Explorador?') { Start-Process explorer.exe $dest } } else { Write-Err "Falha ao exportar drivers (codigo $code)." } } function Restore-PSCDrivers { Write-Section 'Restaurar / Instalar Drivers a partir de uma Pasta' $folder = Read-Host ' Caminho da pasta com os drivers (ex: D:\Drivers_Backup)' if ([string]::IsNullOrWhiteSpace($folder) -or -not (Test-Path -LiteralPath $folder.Trim('"'))) { Write-Warn 'Pasta nao encontrada.' return } $cleanPath = $folder.Trim('"') Write-Info "A instalar todos os drivers (*.inf) de: $cleanPath" [void](Invoke-Native 'pnputil.exe' "/add-driver `"$cleanPath\*.inf`" /subdirs /install") Write-Ok 'Processo de instalacao de drivers concluido.' } # ================================================================ # MODULO 7: CENTRAL DE DRIVERS PSC (AUTO-UPDATE, DIAG, OEM, BACKUP) # ================================================================ function Invoke-PSCDriverDiagnostics { Write-Section 'Raio-X de Dispositivos em Falta / Com Erro no Gestor de Dispositivos' Write-Log '=== INICIO: Diagnostico de Dispositivos PnP ===' Write-Step '1/2' 'A forcar varrimento Plug and Play (pnputil /scan-devices)...' [void](Invoke-Native 'pnputil.exe' '/scan-devices') Write-Step '2/2' 'A analisar todos os dispositivos de hardware (Win32_PnPEntity)...' $errorMap = @{ 1 = 'Code 1: Dispositivo nao configurado corretamente' 3 = 'Code 3: Driver corrompido ou sistema com pouca memoria' 10 = 'Code 10: O dispositivo nao consegue iniciar' 12 = 'Code 12: Recursos insuficientes para este dispositivo' 14 = 'Code 14: Requer reinicio do computador para funcionar' 18 = 'Code 18: Reinstalar os drivers deste dispositivo' 19 = 'Code 19: Registo do Windows corrompido para este dispositivo' 22 = 'Code 22: Dispositivo desativado manualmente' 24 = 'Code 24: Dispositivo ausente ou nao funciona corretamente' 28 = 'Code 28: Os drivers deste dispositivo NAO estao instalados' 31 = 'Code 31: O Windows nao consegue carregar os drivers necessarios' 32 = 'Code 32: O servico deste driver foi desativado no registo' 37 = 'Code 37: O Windows nao consegue inicializar o driver do dispositivo' 39 = 'Code 39: Driver corrompido ou em falta' 43 = 'Code 43: O dispositivo parou porque reportou uma falha de hardware/driver' 45 = 'Code 45: Dispositivo desligado neste momento' 48 = 'Code 48: O driver foi bloqueado por problemas de compatibilidade' 52 = 'Code 52: O Windows nao consegue verificar a assinatura digital do driver' } $problemDevices = @(Get-CimInstance Win32_PnPEntity -ErrorAction SilentlyContinue | Where-Object { $_.ConfigManagerErrorCode -ne 0 }) Write-Host '' if ($problemDevices.Count -eq 0) { Write-Ok 'Excelente! 0 dispositivos em falta ou com triangulo amarelo no Gestor de Dispositivos.' Write-Log 'Diagnostico PnP: 0 dispositivos com erro.' } else { Write-Warn "Foram detetados $($problemDevices.Count) dispositivo(s) com alerta ou sem driver instalado:" Write-Host '' $idx = 0 foreach ($dev in $problemDevices) { $idx++ $errCode = [int]$dev.ConfigManagerErrorCode $errDesc = if ($errorMap.ContainsKey($errCode)) { $errorMap[$errCode] } else { "Code ${errCode}: Erro reportado pelo Gestor de Dispositivos" } $hwId = if ($dev.HardwareID -and $dev.HardwareID.Count -gt 0) { $dev.HardwareID[0] } else { $dev.DeviceID } $cls = if ($dev.PNPClass) { $dev.PNPClass } else { 'Desconhecido' } $color = if ($errCode -eq 28) { 'Red' } elseif ($errCode -eq 22) { 'DarkYellow' } else { 'Yellow' } Write-Host (" [{0}] {1} (Classe: {2})" -f $idx, $dev.Name, $cls) -ForegroundColor $color Write-Host (" Estado : {0}" -f $errDesc) -ForegroundColor Gray Write-Host (" HardwareID : {0}" -f $hwId) -ForegroundColor DarkCyan Write-Log ("Dispositivo c/ erro: {0} | {1} | HWID: {2}" -f $dev.Name, $errDesc, $hwId) } } Write-Host '' $signedDrivers = @(Get-CimInstance Win32_PnPSignedDriver -ErrorAction SilentlyContinue | Where-Object { $_.DriverProviderName -and $_.DriverProviderName -ne 'Microsoft' }) Write-Info "Total de controladores de terceiros (OEM/WHQL) atualmente instalados: $($signedDrivers.Count)" } function Update-PSCDriversOnline { Write-Section 'Atualizacao Automatica de Drivers Online (Microsoft WHQL + Opcionais)' Write-Info 'Pesquisa diretamente no catalogo Microsoft Update todos os drivers para este hardware (incluindo Opcionais).' Write-Log '=== INICIO: Atualizacao Automatica de Drivers Online (COM Microsoft.Update.Session) ===' # 1. Ponto de restauro preventivo Write-Step '1/5' 'A criar Ponto de Restauro preventivo antes de atualizar drivers...' [void](New-PSCRestorePoint 'PSC Toolkit - Antes de Atualizar Drivers') # 2. Garantir servicos do Windows Update ativos e registar Microsoft Update Catalog Write-Step '2/5' 'A preparar servicos Windows Update (wuauserv / bits / cryptsvc) e catalogo Microsoft Update...' foreach ($svc in @('cryptsvc', 'bits', 'wuauserv', 'TrustedInstaller')) { try { Set-Service -Name $svc -StartupType Manual -ErrorAction SilentlyContinue Start-Service -Name $svc -ErrorAction SilentlyContinue } catch { } } try { $svcManager = New-Object -ComObject 'Microsoft.Update.ServiceManager' $svcManager.ClientApplicationID = 'PSC Toolkit Driver Updater' # Regista o catalogo Microsoft Update (7971f918-a847-4430-9279-4a52d1efe18d) para incluir drivers WHQL de terceiros [void]$svcManager.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '') } catch { Write-Info 'Catalogo padrao do Windows Update ativo.' } # 3. Pesquisar todas as atualizacoes do tipo Driver (IsInstalled=0 and Type='Driver') Write-Step '3/5' 'A consultar a Microsoft para detetar drivers em falta ou desatualizados (aguarde 30-90 seg)...' try { $session = New-Object -ComObject 'Microsoft.Update.Session' $session.ClientApplicationID = 'PSC Toolkit Driver Updater' $searcher = $session.CreateUpdateSearcher() $searchResult = $searcher.Search("IsInstalled=0 and Type='Driver'") } catch { Write-Err "Erro ao consultar o catalogo de drivers do Windows Update: $($_.Exception.Message)" Write-Log "ERRO pesquisa drivers COM: $($_.Exception.Message)" return } $updates = $searchResult.Updates if (-not $updates -or $updates.Count -eq 0) { Write-Host '' Write-Ok 'Todos os drivers oficiais WHQL deste equipamento ja estao atualizados!' Write-Log 'Pesquisa de drivers concluida: 0 drivers pendentes.' Invoke-PSCDriverDiagnostics return } Write-Host '' Write-Ok "Foram encontrados $($updates.Count) driver(s) disponiveis para este equipamento:" Write-Host '' $updatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl' $idx = 0 foreach ($u in $updates) { $idx++ $drvClass = if ($u.DriverClass) { $u.DriverClass } else { 'Hardware' } $drvMfg = if ($u.DriverManufacturer) { $u.DriverManufacturer } else { 'OEM' } $drvModel = if ($u.DriverModel) { $u.DriverModel } else { $u.Title } Write-Host (" [{0:D2}] [{1}] {2} - {3}" -f $idx, $drvClass, $drvMfg, $drvModel) -ForegroundColor Cyan Write-Host (" Pacote: {0}" -f $u.Title) -ForegroundColor Gray if (-not $u.EulaAccepted) { try { $u.AcceptEula() } catch { } } [void]$updatesToInstall.Add($u) } Write-Host '' if (-not (Confirm-Action "Descarregar e instalar automaticamente estes $($updatesToInstall.Count) driver(s) agora?")) { Write-Info 'Operacao cancelada pelo tecnico.' return } # 4. Download dos pacotes de drivers Write-Step '4/5' "A descarregar $($updatesToInstall.Count) pacote(s) de drivers oficiais..." try { $downloader = $session.CreateUpdateDownloader() $downloader.Updates = $updatesToInstall $dlResult = $downloader.Download() if ($dlResult.ResultCode -eq 2 -or $dlResult.ResultCode -eq 3) { Write-Ok 'Download dos drivers concluido com sucesso.' } else { Write-Warn "Download terminou com codigo de estado: $($dlResult.ResultCode)" } } catch { Write-Err "Falha durante o download dos drivers: $($_.Exception.Message)" Write-Log "ERRO download drivers: $($_.Exception.Message)" return } # 5. Instalacao dos drivers descarregados Write-Step '5/5' 'A instalar os controladores no sistema (pode piscar o ecra se incluir driver grafico)...' try { $installer = $session.CreateUpdateInstaller() $installer.Updates = $updatesToInstall $instResult = $installer.Install() $statusMap = @{ 0 = 'Nao iniciado' 1 = 'Em curso' 2 = 'INSTALADO COM SUCESSO' 3 = 'Instalado com avisos' 4 = 'FALHOU' 5 = 'Cancelado' } Write-Host '' $installedCount = 0 for ($i = 0; $i -lt $updatesToInstall.Count; $i++) { $itemTitle = $updatesToInstall.Item($i).Title $itemRes = $instResult.GetUpdateResult($i) $codeTxt = if ($statusMap.ContainsKey([int]$itemRes.ResultCode)) { $statusMap[[int]$itemRes.ResultCode] } else { "Codigo $($itemRes.ResultCode)" } if ($itemRes.ResultCode -eq 2 -or $itemRes.ResultCode -eq 3) { $installedCount++ Write-Ok "$itemTitle -> $codeTxt" } else { Write-Warn "$itemTitle -> $codeTxt (HResult: 0x$('{0:X8}' -f $itemRes.HResult))" } Write-Log "Driver Install: $itemTitle -> $codeTxt" } Write-Host '' Write-Ok "Resumo: $installedCount de $($updatesToInstall.Count) driver(s) instalados com sucesso!" if ($instResult.RebootRequired) { Write-Warn 'ATENCAO: Alguns drivers requerem o reinicio do computador para ficarem totalmente ativos.' } } catch { Write-Err "Falha ao instalar os drivers: $($_.Exception.Message)" Write-Log "ERRO instalacao drivers: $($_.Exception.Message)" } # Re-scan PnP final para verificar se restam dispositivos com triangulo amarelo Write-Host '' Invoke-PSCDriverDiagnostics } function Install-PSCOemDriverAssistant { Write-Section 'Assistente Oficial de Drivers do Fabricante (OEM / Chipset / GPU)' $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue $bios = Get-CimInstance Win32_BIOS -ErrorAction SilentlyContinue $gpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue) $mfg = if ($cs.Manufacturer) { $cs.Manufacturer.Trim() } else { 'Desconhecido' } $model = if ($cs.Model) { $cs.Model.Trim() } else { 'Desconhecido' } $gpuNames = ($gpus | ForEach-Object { $_.Name }) -join ' / ' Write-KV 'Fabricante Detetado' $mfg 'Cyan' Write-KV 'Modelo da Maquina' $model 'Cyan' Write-KV 'Placa(s) Grafica(s)' $(if ($gpuNames) { $gpuNames } else { 'n/d' }) 'Cyan' Write-Host '' # Identificar recomendacao automatica conforme fabricante $recBrand = 'Intel' if ($mfg -match 'Dell') { $recBrand = 'Dell' } elseif ($mfg -match 'Lenovo') { $recBrand = 'Lenovo' } elseif ($mfg -match 'HP|Hewlett') { $recBrand = 'HP' } elseif ($mfg -match 'ASUS|ASUSTeK') { $recBrand = 'ASUS' } Write-Info "Marca detetada: $mfg (Recomendado: Utilitario Oficial $recBrand)" Write-Host '' Write-MenuItem '1' 'Dell Command | Update (Oficial Dell - pesquisa e instala BIOS, Chipset e Drivers)' -Recommended:($recBrand -eq 'Dell') Write-MenuItem '2' 'Lenovo System Update (Oficial Lenovo ThinkPad / ThinkCentre / IdeaPad)' -Recommended:($recBrand -eq 'Lenovo') Write-MenuItem '3' 'HP Image Assistant (Oficial HP ProBook / EliteBook / ProDesk - Download Direto)' -Recommended:($recBrand -eq 'HP') Write-MenuItem '4' 'Intel Driver & Support Assistant (Oficial Intel Wi-Fi, Bluetooth, Chipset e iGPU)' -Recommended:($recBrand -eq 'Intel' -or $recBrand -eq 'ASUS') Write-MenuItem '5' 'Executar varrimento silencioso Dell Command | Update CLI (se instalado)' Write-Host '' Write-MenuItem '0' 'Voltar ao menu de Drivers' $choice = Read-Choice switch ($choice) { '1' { if (Test-WingetAvailable) { [void](Install-WingetPackage -Id 'Dell.CommandUpdate' -Name 'Dell Command | Update') $dcuGui = @( "${env:ProgramFiles(x86)}\Dell\CommandUpdate\DellCommandUpdate.exe", "$env:ProgramFiles\Dell\CommandUpdate\DellCommandUpdate.exe" ) | Where-Object { Test-Path $_ } | Select-Object -First 1 if ($dcuGui -and (Confirm-Action 'Abrir o Dell Command | Update agora?')) { Start-Process $dcuGui } } } '2' { if (Test-WingetAvailable) { [void](Install-WingetPackage -Id 'Lenovo.SystemUpdate' -Name 'Lenovo System Update') $lsuGui = @( "${env:ProgramFiles(x86)}\Lenovo\System Update\tvsu.exe", "$env:ProgramFiles\Lenovo\System Update\tvsu.exe" ) | Where-Object { Test-Path $_ } | Select-Object -First 1 if ($lsuGui -and (Confirm-Action 'Abrir o Lenovo System Update agora?')) { Start-Process $lsuGui } } } '3' { Write-Info 'A descarregar HP Image Assistant (HPIA) oficial da HP...' $hpFolder = 'C:\PSC\HPIA' if (-not (Test-Path $hpFolder)) { New-Item -Path $hpFolder -ItemType Directory -Force | Out-Null } $hpExe = Join-Path $hpFolder 'hp-hpia.exe' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Link oficial HP Image Assistant SoftPaq $hpUrl = 'https://ftp.hp.com/pub/caps-softpaq/cmit/softpaq/HPIA.exe' Invoke-WebRequest -Uri $hpUrl -OutFile $hpExe -UseBasicParsing -TimeoutSec 90 -ErrorAction Stop Write-Ok "HPIA descarregado em $hpExe. A extrair..." Start-Process -FilePath $hpExe -ArgumentList "/s /e /f `"$hpFolder`"" -Wait $hpiaBin = Get-ChildItem -Path $hpFolder -Filter 'HPImageAssistant.exe' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 if ($hpiaBin) { Write-Ok "A abrir HP Image Assistant ($($hpiaBin.FullName))..." Start-Process $hpiaBin.FullName } } catch { Write-Warn "Nao foi possivel descarregar HPIA diretamente: $($_.Exception.Message)" Write-Info 'A abrir pagina oficial de drivers HP no navegador...' Start-Process 'https://support.hp.com/pt-pt/drivers' } } '4' { if (Test-WingetAvailable) { [void](Install-WingetPackage -Id 'Intel.IntelDriverAndSupportAssistant' -Name 'Intel Driver & Support Assistant') } } '5' { $dcuCli = @( "${env:ProgramFiles(x86)}\Dell\CommandUpdate\dcu-cli.exe", "$env:ProgramFiles\Dell\CommandUpdate\dcu-cli.exe" ) | Where-Object { Test-Path $_ } | Select-Object -First 1 if (-not $dcuCli) { Write-Warn 'Dell Command | Update CLI (dcu-cli.exe) nao encontrado. Instale primeiro a Opcao [1].' } else { Write-Info 'A executar pesquisa e instalacao automatica Dell Command | Update CLI...' [void](Invoke-Native $dcuCli '/applyUpdates -reboot=disable') } } '0' { return } } } function Show-DriversMenu { while ($true) { Show-Header Write-Host '' Write-Host ' CENTRAL DE DRIVERS PSC (ATUALIZACAO AUTOMATICA, OEM, BACKUP E RESTAURO)' -ForegroundColor DarkYellow Write-Host ' Pesquisa e instalacao 100% nativa via catalogo Microsoft WHQL (inclui Drivers Opcionais)' -ForegroundColor Gray Write-Host '' Write-MenuItem '1' 'Atualizar TODOS os Drivers Automaticamente Online (Microsoft WHQL + Opcionais)' -Recommended Write-MenuItem '2' 'Raio-X de Dispositivos em Falta / Com Erro (!) no Gestor de Dispositivos' -Recommended Write-MenuItem '3' 'Assistente Oficial do Fabricante (Dell Command / Lenovo System Update / HP / Intel)' Write-Host '' Write-MenuItem '4' 'Backup Completo de todos os Drivers atuais desta Maquina (pnputil /export-driver)' Write-MenuItem '5' 'Restaurar / Instalar Drivers a partir de uma pasta local (*.inf)' Write-Host '' Write-MenuItem '6' 'Abrir Gestor de Dispositivos do Windows (devmgmt.msc)' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { Update-PSCDriversOnline; Wait-Return } '2' { Invoke-PSCDriverDiagnostics; Wait-Return } '3' { Install-PSCOemDriverAssistant; Wait-Return } '4' { Backup-PSCDrivers; Wait-Return } '5' { Restore-PSCDrivers; Wait-Return } '6' { Start-Process 'devmgmt.msc' } '0' { return } default { } } } } function Export-PSCWifiProfiles { Write-Section 'Exportar Perfis e Passwords Wi-Fi' $dest = Join-Path $script:PSC.LogDir ("WiFi_{0}_{1}" -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd_HHmmss')) New-Item -Path $dest -ItemType Directory -Force | Out-Null [void](Invoke-Native 'netsh.exe' "wlan export profile key=clear folder=`"$dest`"") $xmls = @(Get-ChildItem -Path $dest -Filter '*.xml' -ErrorAction SilentlyContinue) if ($xmls.Count -eq 0) { Write-Warn 'Nenhum perfil Wi-Fi encontrado nesta maquina.' return } $summaryFile = Join-Path $dest 'Passwords-WiFi.txt' $lines = @("PSC TOOLKIT - PERFIS WI-FI EXPORTADOS ($env:COMPUTERNAME - $(Get-Date -Format 'dd/MM/yyyy HH:mm'))", ('=' * 70)) Write-Host '' foreach ($x in $xmls) { try { [xml]$doc = Get-Content -LiteralPath $x.FullName -Encoding UTF8 $ssid = $doc.WLANProfile.SSIDConfig.SSID.name $pass = $doc.WLANProfile.MSM.security.sharedKey.keyMaterial if (-not $pass) { $pass = '(sem password / aberta / empresarial)' } Write-KV "SSID: $ssid" $pass 'Cyan' $lines += ("SSID: {0,-32} | Password: {1}" -f $ssid, $pass) } catch { } } Set-Content -Path $summaryFile -Value $lines -Encoding UTF8 Write-Host '' Write-Ok "$($xmls.Count) perfis Wi-Fi exportados para: $dest" Write-Info "Resumo legivel guardado em: $summaryFile" } function Import-PSCWifiProfiles { Write-Section 'Importar Perfis Wi-Fi (ficheiros XML)' $folder = Read-Host ' Caminho da pasta com os ficheiros XML Wi-Fi' if ([string]::IsNullOrWhiteSpace($folder) -or -not (Test-Path -LiteralPath $folder.Trim('"'))) { Write-Warn 'Pasta nao encontrada.' return } $xmls = @(Get-ChildItem -Path $folder.Trim('"') -Filter '*.xml' -ErrorAction SilentlyContinue) if ($xmls.Count -eq 0) { Write-Warn 'Nenhum ficheiro .xml encontrado na pasta.'; return } foreach ($x in $xmls) { [void](Invoke-Native 'netsh.exe' "wlan add profile filename=`"$($x.FullName)`" user=all") } Write-Ok "$($xmls.Count) perfis Wi-Fi importados." } function Show-RestorePointsManager { Write-Section 'Pontos de Restauro do Sistema' $pts = @(Get-ComputerRestorePoint -ErrorAction SilentlyContinue) if ($pts.Count -eq 0) { Write-Info 'Nenhum ponto de restauro existente neste momento.' } else { foreach ($p in $pts) { $dt = try { [Management.ManagementDateTimeConverter]::ToDateTime($p.CreationTime) } catch { $p.CreationTime } Write-Host (" #{0,-4} {1:dd-MM-yyyy HH:mm} {2}" -f $p.SequenceNumber, $dt, $p.Description) -ForegroundColor White } } Write-Host '' Write-MenuItem '1' 'Criar novo ponto de restauro agora' -Recommended Write-MenuItem '2' 'Abrir Restauro do Sistema grafico (rstrui.exe)' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { [void](New-PSCRestorePoint 'PSC Toolkit - manual') } '2' { Start-Process 'rstrui.exe' } } } function Show-QuickAdminTools { Write-Section 'Atalhos Rapidos de Bancada' Write-MenuItem '1' 'Gestor de Dispositivos (devmgmt.msc)' Write-MenuItem '2' 'Gestao de Discos (diskmgmt.msc)' Write-MenuItem '3' 'Propriedades do Sistema / Nome da Maquina (sysdm.cpl)' Write-MenuItem '4' 'Programas e Funcionalidades Classico (appwiz.cpl)' Write-MenuItem '5' 'Ligacoes de Rede (ncpa.cpl)' Write-MenuItem '6' 'Configuracao do Sistema (msconfig)' Write-MenuItem '0' 'Voltar' switch (Read-Choice) { '1' { Start-Process 'devmgmt.msc' } '2' { Start-Process 'diskmgmt.msc' } '3' { Start-Process 'sysdm.cpl' } '4' { Start-Process 'appwiz.cpl' } '5' { Start-Process 'ncpa.cpl' } '6' { Start-Process 'msconfig.exe' } } } # --- 6.8 Isolamento & Bloqueio Firewall Adobe / Autodesk --- function Invoke-PSCBlockAdobe { Show-Header Write-Section 'ISOLAMENTO E BLOQUEIO FIREWALL: ADOBE (INBOUND + OUTBOUND)' Write-Log '=== INICIO: Bloqueio Firewall Adobe ===' Write-Step '1/4' 'A parar e desativar servicos de telemetria Adobe (AGMService / AGSService)...' $adobeServices = @('AGMService', 'AGSService', 'AdobeARMservice', 'AdobeUpdateService') foreach ($svcName in $adobeServices) { $svc = Get-Service -Name $svcName -ErrorAction SilentlyContinue if ($svc) { Stop-Service -Name $svcName -Force -ErrorAction SilentlyContinue Set-Service -Name $svcName -StartupType Disabled -ErrorAction SilentlyContinue Write-OK "Servico desativado: $svcName" } } try { Get-ScheduledTask -TaskName '*AdobeGCInvoker*', '*AdobeAAMUpdater*', '*Adobe-Genuine*' -ErrorAction SilentlyContinue | Disable-ScheduledTask -ErrorAction SilentlyContinue | Out-Null Write-OK 'Tarefas agendadas Adobe Genuine desativadas.' } catch { } Write-Step '2/4' 'A localizar todos os executaveis (.exe) nas pastas Adobe...' $adobeFolders = @( "$env:ProgramFiles\Adobe", "${env:ProgramFiles(x86)}\Adobe", "$env:ProgramFiles\Common Files\Adobe", "${env:ProgramFiles(x86)}\Common Files\Adobe", "$env:ProgramData\Adobe", "$env:LOCALAPPDATA\Adobe" ) $allAdobeExes = @() foreach ($folder in $adobeFolders) { if (Test-Path $folder) { Write-Info "A indexar: $folder" $found = Get-ChildItem -Path $folder -Filter '*.exe' -Recurse -File -ErrorAction SilentlyContinue if ($found) { $allAdobeExes += $found } } } $allAdobeExes = $allAdobeExes | Sort-Object -Property FullName -Unique if (-not $allAdobeExes -or $allAdobeExes.Count -eq 0) { Write-Warn 'Nenhum executavel Adobe encontrado nas pastas predefinidas.' return } Write-OK "Foram encontrados $($allAdobeExes.Count) executaveis Adobe unicos." Write-Step '3/4' 'A limpar regras antigas (PSC_Block_Adobe_*) para evitar duplicados...' $oldRules = Get-NetFirewallRule -DisplayName 'PSC_Block_Adobe_*' -ErrorAction SilentlyContinue if ($oldRules) { $oldRules | Remove-NetFirewallRule -ErrorAction SilentlyContinue Write-OK "Removidas $($oldRules.Count) regras antigas PSC_Block_Adobe_*." } Write-Step '4/4' 'A criar regras de bloqueio Bidirecional (Inbound + Outbound) na Firewall...' $counter = 0 foreach ($exe in $allAdobeExes) { $counter++ $ruleOut = ('PSC_Block_Adobe_Out_{0:D4}_{1}' -f $counter, $exe.Name) $ruleIn = ('PSC_Block_Adobe_In_{0:D4}_{1}' -f $counter, $exe.Name) New-NetFirewallRule -DisplayName $ruleOut ` -Direction Outbound ` -Program $exe.FullName ` -Action Block ` -Profile Any ` -Description "Bloqueado por PSC Toolkit ($($exe.FullName))" ` -ErrorAction SilentlyContinue | Out-Null New-NetFirewallRule -DisplayName $ruleIn ` -Direction Inbound ` -Program $exe.FullName ` -Action Block ` -Profile Any ` -Description "Bloqueado por PSC Toolkit ($($exe.FullName))" ` -ErrorAction SilentlyContinue | Out-Null Write-Host " [$counter/$($allAdobeExes.Count)] Bloqueado (IN/OUT): $($exe.Name)" -ForegroundColor Green } Write-Host '' Write-OK "Isolamento Adobe concluido! $counter executaveis bloqueados ($($counter * 2) regras In/Out)." Write-Log "Isolamento Adobe concluido: $counter executaveis bloqueados" } function Invoke-PSCBlockAutodesk { Show-Header Write-Section 'ISOLAMENTO E EXCLUSOES DEFENDER + FIREWALL: AUTODESK' Write-Log '=== INICIO: Isolamento e Bloqueio Autodesk ===' Write-Step '1/4' 'A configurar exclusoes cirurgicas no Microsoft Defender (Autodesk / FLEXnet)...' $staticExclusions = @( 'C:\Program Files\Autodesk', 'C:\Program Files (x86)\Autodesk', 'C:\Program Files\Common Files\Autodesk Shared', 'C:\Program Files (x86)\Common Files\Autodesk Shared', 'C:\Program Files\Common Files\Macrovision Shared', 'C:\Program Files (x86)\Common Files\Macrovision Shared', 'C:\ProgramData\Autodesk', 'C:\ProgramData\FLEXnet' ) foreach ($path in $staticExclusions) { try { Add-MpPreference -ExclusionPath $path -ErrorAction Stop Write-OK "Exclusao Defender adicionada: $path" } catch { Write-Warn "Nao foi possivel adicionar exclusao Defender para: $path" } } $userProfiles = Get-ChildItem -Path 'C:\Users' -Directory -ErrorAction SilentlyContinue foreach ($profile in $userProfiles) { $activatorPath = Join-Path -Path $profile.FullName -ChildPath 'ACTIVATOR AUTOCAD' if (Test-Path -Path $activatorPath) { try { Add-MpPreference -ExclusionPath $activatorPath -ErrorAction Stop Write-OK "Exclusao Defender adicionada (Utilizador $($profile.Name)): $activatorPath" } catch { } } } Write-Step '2/4' 'A localizar todos os executaveis (.exe) nas pastas Autodesk...' $autodeskFolders = @( 'C:\Program Files\Autodesk', 'C:\Program Files (x86)\Autodesk', 'C:\Program Files\Common Files\Autodesk Shared', 'C:\Program Files (x86)\Common Files\Autodesk Shared', 'C:\ProgramData\Autodesk', "$env:LOCALAPPDATA\Autodesk" ) $allAutodeskExes = @() foreach ($folder in $autodeskFolders) { if (Test-Path -Path $folder) { Write-Info "A indexar: $folder" $found = Get-ChildItem -Path $folder -Filter '*.exe' -Recurse -File -ErrorAction SilentlyContinue if ($found) { $allAutodeskExes += $found } } } $allAutodeskExes = $allAutodeskExes | Sort-Object -Property FullName -Unique if (-not $allAutodeskExes -or $allAutodeskExes.Count -eq 0) { Write-Warn 'Nenhum executavel Autodesk encontrado nas pastas predefinidas.' return } Write-OK "Foram encontrados $($allAutodeskExes.Count) executaveis Autodesk unicos." Write-Step '3/4' 'A limpar regras antigas (PSC_Block_Autodesk_*) para evitar colisoes...' $oldRules = Get-NetFirewallRule -DisplayName 'PSC_Block_Autodesk_*' -ErrorAction SilentlyContinue if ($oldRules) { $oldRules | Remove-NetFirewallRule -ErrorAction SilentlyContinue Write-OK "Removidas $($oldRules.Count) regras antigas PSC_Block_Autodesk_*." } Write-Step '4/4' 'A criar regras de bloqueio Bidirecional (Inbound + Outbound) na Firewall...' $counter = 0 foreach ($exe in $allAutodeskExes) { $counter++ $ruleOut = ('PSC_Block_Autodesk_{0:D4}_{1} - OUT' -f $counter, $exe.Name) $ruleIn = ('PSC_Block_Autodesk_{0:D4}_{1} - IN' -f $counter, $exe.Name) New-NetFirewallRule -DisplayName $ruleOut ` -Direction Outbound ` -Program $exe.FullName ` -Action Block ` -Profile Any ` -Description "Bloqueio automatico PSC ($($exe.FullName))" ` -ErrorAction SilentlyContinue | Out-Null New-NetFirewallRule -DisplayName $ruleIn ` -Direction Inbound ` -Program $exe.FullName ` -Action Block ` -Profile Any ` -Description "Bloqueio automatico PSC ($($exe.FullName))" ` -ErrorAction SilentlyContinue | Out-Null Write-Host " [$counter/$($allAutodeskExes.Count)] Bloqueado (IN/OUT): $($exe.Name)" -ForegroundColor Green } Write-Host '' Write-OK "Isolamento Autodesk concluido! $counter executaveis bloqueados ($($counter * 2) regras In/Out)." Write-Log "Isolamento Autodesk concluido: $counter executaveis bloqueados" } function Remove-PSCAppFirewallRules { param([Parameter(Mandatory)][ValidateSet('Adobe','Autodesk')] [string]$Vendor) Show-Header Write-Section "REVERTER / REMOVER REGRAS DE FIREWALL: $($Vendor.ToUpper())" $pattern = "PSC_Block_${Vendor}_*" $rules = Get-NetFirewallRule -DisplayName $pattern -ErrorAction SilentlyContinue if (-not $rules) { Write-Info "Nenhuma regra '$pattern' encontrada na Firewall do Windows." return } $count = @($rules).Count $rules | Remove-NetFirewallRule -ErrorAction SilentlyContinue Write-OK "Foram removidas $count regras de Firewall ($pattern) com sucesso!" Write-Log "Removidas $count regras de Firewall ($pattern)" } function Show-PSCAdobeAutodeskMenu { while ($true) { Show-Header Write-Host '' Write-Host ' ISOLAMENTO & BLOQUEIO FIREWALL: ADOBE / AUTODESK' -ForegroundColor DarkYellow Write-Host ' Bloqueio bidirecional (In/Out) sem colisao de nomes + desativacao AGM/AGS + Defender' -ForegroundColor Gray Write-Host '' Write-MenuItem '1' 'Isolar e Bloquear ADOBE (Desativa AGM/AGS + Bloqueia .exe na Firewall In/Out)' -Recommended Write-MenuItem '2' 'Isolar e Bloquear AUTODESK (Exclusoes Defender/FLEXnet + Firewall In/Out)' -Recommended Write-Host '' Write-MenuItem '3' 'Reverter / Remover todas as regras Firewall ADOBE (PSC_Block_Adobe_*)' Write-MenuItem '4' 'Reverter / Remover todas as regras Firewall AUTODESK (PSC_Block_Autodesk_*)' Write-Host '' Write-MenuItem '0' 'Voltar ao menu anterior' switch (Read-Choice) { '1' { Invoke-PSCBlockAdobe; Wait-Return } '2' { Invoke-PSCBlockAutodesk; Wait-Return } '3' { Remove-PSCAppFirewallRules -Vendor 'Adobe'; Wait-Return } '4' { Remove-PSCAppFirewallRules -Vendor 'Autodesk'; Wait-Return } '0' { return } default { } } } } function Show-UtilitiesMenu { while ($true) { Show-Header Write-Host '' Write-Host ' UTILITARIOS, VPN SSTP E RELATORIO EXECUTIVO PSC' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Gerar Relatorio Executivo de Bancada PSC (HTML A4 imprimivel / PDF)' -Recommended Write-MenuItem 'U' 'Enviar Raio-X Forense p/ Antigravity + Log / Relatorio HTML (1 clique)' -Recommended Write-Host '' Write-MenuItem '2' 'Backup de todos os Drivers de terceiros (pnputil /export-driver)' Write-MenuItem '3' 'Restaurar / Instalar Drivers a partir de uma pasta' Write-Host '' Write-MenuItem '4' 'Exportar Perfis e Passwords Wi-Fi (mostra no ecra + guarda XML/TXT)' Write-MenuItem '5' 'Importar Perfis Wi-Fi a partir de pasta XML' Write-Host '' Write-MenuItem '6' 'Gerir / Criar Pontos de Restauro do Sistema (rstrui)' Write-MenuItem '7' 'Atalhos rapidos de administracao (Dispositivos, Discos, Rede, sysdm.cpl)' Write-MenuItem '8' 'Central VPN SSTP PSC (Modo Cliente sem .cer + Modo Servidor RRAS + Diagnostico)' -Recommended Write-MenuItem '9' 'Isolamento & Bloqueio Firewall Adobe / Autodesk (Defender + In/Out)' -Recommended Write-Host '' Write-MenuItem '0' 'Voltar ao menu principal' switch (Read-Choice) { '1' { New-PSCInterventionReport; Wait-Return } 'U' { Send-PSCLogsToPortal; Wait-Return } '2' { Backup-PSCDrivers; Wait-Return } '3' { Restore-PSCDrivers; Wait-Return } '4' { Export-PSCWifiProfiles; Wait-Return } '5' { Import-PSCWifiProfiles; Wait-Return } '6' { Show-RestorePointsManager; Wait-Return } '7' { Show-QuickAdminTools } '8' { Show-PSCSstpMenu } '9' { Show-PSCAdobeAutodeskMenu } '0' { return } default { } } } } # ================================================================ # MENU PRINCIPAL # ================================================================ function Show-ComingSoon { Write-Info 'Modulo em desenvolvimento - disponivel numa proxima versao.' Wait-Return } function Show-MainMenu { while ($true) { Show-Header Write-Host '' Write-Host ' MENU PRINCIPAL' -ForegroundColor DarkYellow Write-Host '' Write-MenuItem '1' 'Reparacao do Sistema Operativo' Write-MenuItem '2' 'Arranque e Performance' Write-MenuItem '3' 'Limpeza Profunda' Write-MenuItem '4' 'Diagnostico e Hardware' Write-MenuItem '5' 'Pos-Instalacao (100% Download Direto CDN + TV QS c/ Logo PSC)' Write-MenuItem '6' 'Utilitarios, VPN SSTP, Firewall Adobe/Autodesk e Relatorio PSC' Write-MenuItem '7' 'Central de Drivers PSC (Atualizacao Automatica, OEM, Backup e Restauro)' -Recommended Write-Host '' Write-MenuItem 'U' 'Enviar Raio-X Forense p/ Antigravity + Log para o Portal PSC' -Recommended Write-MenuItem 'L' 'Abrir pasta de logs (C:\PSC\Logs)' Write-MenuItem '0' 'Sair' switch (Read-Choice) { '1' { Show-RepairMenu } '2' { Show-PerformanceMenu } '3' { Show-CleanupMenu } '4' { Show-DiagnosticsMenu } '5' { Show-PostInstallMenu } '6' { Show-UtilitiesMenu } '7' { Show-DriversMenu } 'U' { Send-PSCLogsToPortal; Wait-Return } 'L' { Start-Process explorer.exe $script:PSC.LogDir } '0' { return } default { } } } } # ================================================================ Start-PSCToolkit