# ============================================================ 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)) + ')' } "
Pro Service Computer (PSC) • Cascais / Lisboa • Portugal
Tlm: +351 914 104 710 • Email: geral@proservicecomputer.pt • proservicecomputer.pt
| Disco Físico | Tipo / Barramento | Capacidade | Temp. / Desgaste | Estado SMART |
|---|
| Volume Lógico | Espaço Livre | Total | % Livre | Estado |
|---|
| Área | Verificação | Resultado | Estado |
|---|