# ============================================================================ # PSC SERVER TOOLKIT v1.0.0 - CONSOLA EXCLUSIVA DE SERVIDORES (WINDOWS SERVER) # Pro Service Computer (PSC) | Cascais / Lisboa | +351 914 104 710 # Endpoint: irm https://portal.proservicecomputer.pt/servidores | iex # ============================================================================ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $ErrorActionPreference = 'Continue' try { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force -ErrorAction SilentlyContinue } catch {} $Global:PSCServerVersion = '1.1.0' $Global:PSCBackupDir = 'C:\PSC-BACKUP' $Global:PSCPlansDir = 'C:\PSC-BACKUP\plans' $Global:PSCConfigFile = 'C:\PSC-BACKUP\config.json' $Global:PSCRunnerFile = 'C:\PSC-BACKUP\psc-backup-runner.ps1' $Global:PSCLogFile = 'C:\PSC-BACKUP\backup_robocopy.log' $Global:PSCStatusFile = 'C:\PSC-BACKUP\last_status.json' $Global:PSCTaskName = 'PSC_Enterprise_Backup' $Global:PSCWatchdogDir = 'C:\PSC-WATCHDOG' $Global:PSCPortalUrl = 'https://portal.proservicecomputer.pt/servidores/upload_log.php' $Global:PSCPortalToken = 'psc-servidores-2026' # Auto-elevacao para Administrador se necessario $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host "[PSC] A elevar privilegios para Administrador..." -ForegroundColor Yellow $argList = "-NoProfile -ExecutionPolicy Bypass -Command `"[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; irm https://portal.proservicecomputer.pt/servidores | iex`"" Start-Process powershell.exe -Verb RunAs -ArgumentList $argList return } foreach ($d in @($Global:PSCBackupDir, $Global:PSCPlansDir, $Global:PSCWatchdogDir)) { if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null } } function Get-PSCPlanPaths([string]$planId = '') { $cleanId = ($planId -replace '[^A-Za-z0-9_-]', '_').Trim('_') if ([string]::IsNullOrWhiteSpace($cleanId) -or $cleanId -eq 'PRINCIPAL') { return [PSCustomObject]@{ PlanId = 'PRINCIPAL' IsDefault = $true ConfigFile = $Global:PSCConfigFile LogFile = $Global:PSCLogFile StatusFile = $Global:PSCStatusFile TaskName = $Global:PSCTaskName } } return [PSCustomObject]@{ PlanId = $cleanId IsDefault = $false ConfigFile = (Join-Path $Global:PSCPlansDir "$cleanId.json") LogFile = (Join-Path $Global:PSCBackupDir "backup_robocopy_$cleanId.log") StatusFile = (Join-Path $Global:PSCBackupDir "last_status_$cleanId.json") TaskName = "$($Global:PSCTaskName)_$cleanId" } } function Get-PSCAllPlans { $plans = @() if (Test-Path $Global:PSCConfigFile) { try { $c = Get-Content $Global:PSCConfigFile -Raw -Encoding UTF8 | ConvertFrom-Json $plans += [PSCustomObject]@{ Paths = (Get-PSCPlanPaths 'PRINCIPAL'); Config = $c } } catch {} } if (Test-Path $Global:PSCPlansDir) { foreach ($pf in (Get-ChildItem $Global:PSCPlansDir -Filter '*.json' -ErrorAction SilentlyContinue | Sort-Object Name)) { try { $pId = [System.IO.Path]::GetFileNameWithoutExtension($pf.Name) $c = Get-Content $pf.FullName -Raw -Encoding UTF8 | ConvertFrom-Json $plans += [PSCustomObject]@{ Paths = (Get-PSCPlanPaths $pId); Config = $c } } catch {} } } return $plans } function Select-PSCPlan([string]$promptTitle = 'Selecionar Plano de Backup') { $plans = @(Get-PSCAllPlans) if ($plans.Count -eq 0) { return $null } if ($plans.Count -eq 1) { return $plans[0] } Write-Host "`n $promptTitle" -ForegroundColor Yellow for ($i = 0; $i -lt $plans.Count; $i++) { $p = $plans[$i] Write-Host (" [{0}] {1,-16} -> {2} ({3} as {4})" -f ($i + 1), $p.Paths.PlanId, $p.Config.DestinoBase, $p.Config.Periodicidade, $p.Config.Horario) -ForegroundColor White } $sel = Read-Host "`n Escolha o numero do plano (Enter para [1])" $idx = 1 if (-not [string]::IsNullOrWhiteSpace($sel)) { [void][int]::TryParse($sel, [ref]$idx) } if ($idx -lt 1 -or $idx -gt $plans.Count) { $idx = 1 } return $plans[$idx - 1] } function Get-PSCBackupConfig([string]$planId = '') { $p = Get-PSCPlanPaths $planId if (Test-Path $p.ConfigFile) { try { return (Get-Content $p.ConfigFile -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { return $null } } return $null } function Escape-JsonStr([string]$s) { if ($null -eq $s) { return '' } return $s.Replace('\', '\\').Replace('"', '\"').Replace("`r", '\r').Replace("`n", '\n').Replace("`t", '\t') } function Save-PSCBackupConfig($cfgObj, [string]$planId = '') { $p = Get-PSCPlanPaths $planId $parentDir = [System.IO.Path]::GetDirectoryName($p.ConfigFile) if (-not [System.IO.Directory]::Exists($parentDir)) { [System.IO.Directory]::CreateDirectory($parentDir) | Out-Null } $lines = New-Object System.Collections.Generic.List[string] foreach ($prop in $cfgObj.PSObject.Properties) { $k = Escape-JsonStr $prop.Name $v = $prop.Value if ($v -is [bool]) { $lines.Add(" `"$k`": " + ($(if ($v) { 'true' } else { 'false' }))) } elseif ($v -is [System.Array]) { $items = @($v | ForEach-Object { "`"" + (Escape-JsonStr ([string]$_)) + "`"" }) -join ', ' $lines.Add(" `"$k`": [$items]") } elseif ($v -is [int] -or $v -is [double] -or $v -is [long]) { $lines.Add(" `"$k`": $v") } else { $lines.Add(" `"$k`": `"" + (Escape-JsonStr ([string]$v)) + "`"") } } $jsonOut = "{`r`n" + ($lines -join ",`r`n") + "`r`n}" [System.IO.File]::WriteAllText($p.ConfigFile, $jsonOut, (New-Object System.Text.UTF8Encoding($false))) } function Write-PSCServerHeader { Clear-Host $host.UI.RawUI.WindowTitle = "PSC Server Toolkit v$Global:PSCServerVersion - Pro Service Computer" Write-Host "============================================================================" -ForegroundColor DarkYellow Write-Host " PRO SERVICE COMPUTER (PSC) - SERVER TOOLKIT v$Global:PSCServerVersion (WINDOWS SERVER)" -ForegroundColor Yellow Write-Host " Backups 00h01 Sem Apagar | VPN SSTP RRAS + Watchdog | DynDNS | SQL & ERP" -ForegroundColor Gray Write-Host "============================================================================" -ForegroundColor DarkYellow $osCaption = 'Windows' try { $osCaption = (Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue).Caption } catch {} Write-Host (" Servidor : {0} ({1}) | Utilizador: {2}" -f $env:COMPUTERNAME, $osCaption, $env:USERNAME) -ForegroundColor White $allPlans = @(Get-PSCAllPlans) if ($allPlans.Count -gt 0) { foreach ($pl in $allPlans) { $c = $pl.Config $pId = $pl.Paths.PlanId Write-Host (" Backup [{0,-10}] : Cliente [{1}] -> [{2}] ({3} as {4})" -f $pId, $c.Cliente, $c.DestinoBase, $c.Periodicidade, $c.Horario) -ForegroundColor Green if (Test-Path $pl.Paths.StatusFile) { try { $st = Get-Content $pl.Paths.StatusFile -Raw | ConvertFrom-Json $color = if ($st.Estado -eq 'SUCCESS') { 'Green' } elseif ($st.Estado -eq 'WARNING') { 'Yellow' } else { 'Red' } $pctInfo = if ($null -ne $st.OcupacaoPercent) { "$($st.OcupacaoPercent)% usado" } else { "Livre: $($st.EspacoLivreDestino)" } Write-Host (" Ultimo [{0}] : {1} em {2} ({3}s | Disco: {4} | Falhas: {5})" -f $pId, $st.Estado, $st.DataHora, $st.DuracaoSegundos, $pctInfo, $st.FicheirosFalhados) -ForegroundColor $color } catch {} } } } else { Write-Host " Backup Ativo : [NAO CONFIGURADO NESTE SERVIDOR]" -ForegroundColor Yellow } $stVpn = if ($taskVpn) { "ATIVO ($($taskVpn.State))" } else { 'INATIVO' } $stDns = if ($taskDns) { "ATIVO ($($taskDns.State))" } else { 'INATIVO' } $stErp = if ($taskErp) { "ATIVO ($($taskErp.State))" } else { 'INATIVO' } Write-Host (" Watchdogs PSC : VPN (5m): [{0}] | DynDNS (10m): [{1}] | SQL/ERP: [{2}]" -f $stVpn, $stDns, $stErp) -ForegroundColor Gray Write-Host "============================================================================" -ForegroundColor DarkYellow } # ============================================================================ # MODULO 1: BACKUPS DE SERVIDOR (ROBOCOPY INCREMENTAL SEM APAGAR) # ============================================================================ function Build-PSCRunnerScript { $runnerCode = @' # ============================================================================ # PSC ENTERPRISE BACKUP RUNNER v1.4.1 (PSC_RUNNER_V3) - EXECUCAO AUTONOMA AGENDADA # - Backup Incremental Sem Apagar no Destino (/E /XO) # - Monitorizacao de % de Ocupacao do Disco de Destino (Local ou NAS SMB) # - Ao fim de 6 meses: NAO formata automaticamente; envia Alerta/Recomendacao # para backups@proservicecomputer.pt a informar que o disco tem +6 meses # ============================================================================ param( [string]$PlanId = '', [switch]$ForceTelegram, [switch]$TestSixMonthAlert ) [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $ErrorActionPreference = 'Continue' try { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force -ErrorAction SilentlyContinue } catch {} $cleanPlan = ($PlanId -replace '[^A-Za-z0-9_-]', '_').Trim('_') $isCustomPlan = (-not [string]::IsNullOrWhiteSpace($cleanPlan) -and $cleanPlan -ne 'PRINCIPAL') if ($isCustomPlan) { $configFile = "C:\PSC-BACKUP\plans\$cleanPlan.json" $logFile = "C:\PSC-BACKUP\backup_robocopy_$cleanPlan.log" $statusFile = "C:\PSC-BACKUP\last_status_$cleanPlan.json" $mutexName = "Global\PSC_Enterprise_Backup_Lock_$cleanPlan" $planSuffix = "__$cleanPlan" } else { $cleanPlan = 'PRINCIPAL' $configFile = 'C:\PSC-BACKUP\config.json' $logFile = 'C:\PSC-BACKUP\backup_robocopy.log' $statusFile = 'C:\PSC-BACKUP\last_status.json' $mutexName = 'Global\PSC_Enterprise_Backup_Lock' $planSuffix = '' } $portalUrl = 'https://portal.proservicecomputer.pt/servidores/upload_log.php' $token = 'psc-servidores-2026' if (-not (Test-Path $configFile)) { Write-Host "[ERRO] Ficheiro de configuracao nao encontrado: $configFile" -ForegroundColor Red exit 1 } $cfg = Get-Content $configFile -Raw -Encoding UTF8 | ConvertFrom-Json $startDt = Get-Date $startStr = $startDt.ToString('yyyy-MM-dd HH:mm:ss') function Write-RunnerLog([string]$msg, [string]$color = 'White') { $ts = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') $line = "[$ts] $msg" Write-Host $line -ForegroundColor $color try { Add-Content -Path $logFile -Value $line -Encoding UTF8 } catch {} } $lockCreated = $false $lockFile = "$statusFile.lock" if (Test-Path $lockFile) { $lockBusy = $false try { $oldPid = [int]((Get-Content $lockFile -Raw -ErrorAction SilentlyContinue).Trim()) $oldProc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue if ($oldProc -and $oldProc.ProcessName -match 'powershell' -and ((Get-Date) - (Get-Item $lockFile).LastWriteTime).TotalHours -lt 12) { $lockBusy = $true } } catch {} if ($lockBusy) { Write-RunnerLog "[AVISO] Outra instancia de PSC Backup (PID $oldPid) ja esta em execucao. A sair." "Yellow" exit 0 } } try { [System.IO.File]::WriteAllText($lockFile, "$PID", (New-Object System.Text.UTF8Encoding($false))) } catch {} function Format-BytesHuman([double]$bytes) { if ($bytes -ge 1TB) { return "{0:N2} TB" -f ($bytes / 1TB) } if ($bytes -ge 1GB) { return "{0:N1} GB" -f ($bytes / 1GB) } return "{0:N0} MB" -f ($bytes / 1MB) } function Get-TargetDiskStats([string]$targetPath) { $res = [PSCustomObject]@{ FreeStr = 'N/D'; TotalStr = 'N/D'; UsedPct = $null } try { if (-not ("PSCDiskApi.NativeDisk" -as [type])) { Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; namespace PSCDiskApi { public class NativeDisk { [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); } } "@ } [uint64]$freeAvail = 0 [uint64]$totalBytes = 0 [uint64]$totalFree = 0 if ([PSCDiskApi.NativeDisk]::GetDiskFreeSpaceEx($targetPath, [ref]$freeAvail, [ref]$totalBytes, [ref]$totalFree)) { if ($totalBytes -gt 0) { $usedBytes = [double]$totalBytes - [double]$freeAvail $pct = [Math]::Round(($usedBytes / [double]$totalBytes) * 100.0, 1) $res.FreeStr = Format-BytesHuman ([double]$freeAvail) $res.TotalStr = Format-BytesHuman ([double]$totalBytes) $res.UsedPct = $pct } } } catch {} return $res } if (Test-Path $logFile) { if ((Get-Item $logFile).Length -gt 10MB) { Move-Item $logFile "$logFile.old" -Force -ErrorAction SilentlyContinue } } Write-RunnerLog "==========================================================" "Cyan" Write-RunnerLog " PSC BACKUP RUNNER - CLIENTE: $($cfg.Cliente) ($env:COMPUTERNAME)" "Yellow" Write-RunnerLog "==========================================================" "Cyan" $destBase = $cfg.DestinoBase $connected = $false # 1. Resolver ligacao SMB / NAS ou Disco de Destino if ($cfg.TipoDestino -eq 'SMB') { $nasHost = $cfg.NasHost $nasIp = $cfg.NasIpFallback $nasShare= $cfg.NasSharePath $nasUser = $cfg.NasUser $nasPass = $cfg.NasPass $candidateHost = $nasHost Write-RunnerLog "[1/5] A ligar ao NAS via Hostname (\\$candidateHost\$nasShare)..." "Cyan" try { net use "\\$candidateHost\IPC$" /delete /y 2>$null | Out-Null if ($nasUser -and $nasPass) { $null = net use "\\$candidateHost\IPC$" $nasPass /user:$nasUser 2>&1 } if (Test-Path "\\$candidateHost\$nasShare") { $connected = $true $destBase = "\\$candidateHost\$nasShare" Write-RunnerLog "Ligacao SMB estabelecida: $destBase" "Green" } } catch {} if ((-not $connected) -and $nasIp) { Write-RunnerLog "Falha por nome. A tentar fallback por IP (\\$nasIp\$nasShare)..." "Yellow" try { net use "\\$nasIp\IPC$" /delete /y 2>$null | Out-Null if ($nasUser -and $nasPass) { $null = net use "\\$nasIp\IPC$" $nasPass /user:$nasUser 2>&1 } if (Test-Path "\\$nasIp\$nasShare") { $connected = $true $destBase = "\\$nasIp\$nasShare" Write-RunnerLog "Ligacao SMB estabelecida via IP: $destBase" "Green" } } catch {} } } else { if ($destBase -match '^[A-Za-z]:$') { $destBase = "$destBase\" } Write-RunnerLog "[1/5] A verificar disco/destino ($destBase)..." "Cyan" $driveRoot = Split-Path -Path $destBase -Qualifier -ErrorAction SilentlyContinue if ($driveRoot -and (Test-Path $driveRoot)) { if (-not (Test-Path $destBase)) { try { New-Item -ItemType Directory -Path $destBase -Force | Out-Null } catch {} } } if (Test-Path $destBase) { $connected = $true Write-RunnerLog "Disco de destino acessivel: $destBase" "Green" } } if (-not $connected) { $errMsg = "Disco ou NAS de destino inacessivel ($destBase). Verifique se o suporte esta ligado." Write-RunnerLog "[ERRO CRITICO] $errMsg" "Red" $failObj = @{ Cliente = $cfg.Cliente Maquina = $env:COMPUTERNAME PlanoId = $cleanPlan Estado = 'FAILED' Mensagem = $errMsg Destino = $cfg.DestinoBase EspacoLivreDestino = 'INACESSIVEL' EspacoTotalDestino = 'N/D' OcupacaoPercent = $null HorarioAgendado = $cfg.Horario Periodicidade = $cfg.Periodicidade Modo = $cfg.Modo DataInicioCiclo = $cfg.DataInicioCiclo DataProximaFormatacao6M = $cfg.DataProximaFormatacao6M Alerta6Meses = $false EmailRelatorio = $cfg.EmailRelatorio EnviarEmailRelatorio = $cfg.EnviarEmailRelatorio FicheirosCopiados = 0 FicheirosFalhados = 1 DuracaoSegundos = 0 DataHora = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') PastasIncluidas = @($cfg.Origens) ResumoLog = $errMsg ForceTelegramAlert = $true } $jsonFail = $failObj | ConvertTo-Json -Depth 5 $jsonFail | Set-Content -Path $statusFile -Encoding UTF8 try { $cleanClient = ($cfg.Cliente -replace '[^A-Za-z0-9_-]', '_') $cleanHost = ($env:COMPUTERNAME -replace '[^A-Za-z0-9_-]', '_') $body = @{ token = $token host = $env:COMPUTERNAME filename = "Backup-PSC_${cleanClient}_${cleanHost}${planSuffix}.json" content = $jsonFail } Invoke-RestMethod -Uri $portalUrl -Method Post -Body $body -TimeoutSec 15 | Out-Null } catch {} exit 1 } # 2. Verificar se ja ultrapassou 6 meses de informacao acumulada (Apenas Aviso - Sem Formatar!) $alerta6Meses = $false if ($TestSixMonthAlert) { $alerta6Meses = $true } elseif ($cfg.AtivarRotacao6Meses) { try { $nextDate = [datetime]::ParseExact($cfg.DataProximaFormatacao6M, 'yyyy-MM-dd', $null) if ((Get-Date) -ge $nextDate) { $alerta6Meses = $true } } catch {} } if ($alerta6Meses) { Write-RunnerLog "[2/5] AVISO 6 MESES: O disco de destino ($destBase) ja acumula +6 meses de dados antigos (desde $($cfg.DataInicioCiclo)). Recomenda-se formatacao limpa." "Yellow" } else { Write-RunnerLog "[2/5] Ciclo de 6 meses em dia. Proxima recomendacao de limpeza em: $($cfg.DataProximaFormatacao6M)" "Gray" } # 3. Fecho suave do Outlook se ativado $outlookWasRunning = $false if ($cfg.FecharOutlook) { $olProc = Get-Process 'OUTLOOK' -ErrorAction SilentlyContinue if ($olProc) { $outlookWasRunning = $true Write-RunnerLog "[3/5] Outlook em execucao. A fechar suavemente para libertar ficheiros PST..." "Yellow" foreach ($p in $olProc) { try { $p.CloseMainWindow() | Out-Null } catch {} } Start-Sleep -Seconds 5 if (Get-Process 'OUTLOOK' -ErrorAction SilentlyContinue) { Start-Sleep -Seconds 3 } } else { Write-RunnerLog "[3/5] Outlook ja se encontra fechado." "Gray" } } else { Write-RunnerLog "[3/5] Gestao de Outlook desativada neste plano." "Gray" } # 4. Executar Robocopy Incremental (Sem apagar no destino por predefinicao) Write-RunnerLog "[4/5] A sincronizar pastas com Robocopy (Modo: $($cfg.Modo))..." "Cyan" $totalCopied = 0 $totalFailed = 0 $excludeDirs = @('node_modules', '.git', 'cache', '.cache', 'tmp', 'Temp', 'OneDrive', 'System Volume Information', '$RECYCLE.BIN') $excludeArgs = @($excludeDirs | ForEach-Object { "`"$_`"" }) foreach ($src in @($cfg.Origens)) { if (-not (Test-Path $src)) { Write-RunnerLog "[AVISO] Pasta de origem nao encontrada: $src" "Yellow" continue } $srcClean = $src.TrimEnd('\') if ($srcClean -match '^[A-Za-z]:$') { $folderLeaf = "Drive_" + ($srcClean.Substring(0,1)) } else { $folderLeaf = Split-Path -Path $srcClean -Leaf if ([string]::IsNullOrWhiteSpace($folderLeaf)) { $folderLeaf = 'Dados' } } $targetSub = Join-Path $destBase "$($env:COMPUTERNAME)\$folderLeaf" $dstClean = $targetSub.TrimEnd('\') if (-not (Test-Path $dstClean)) { try { New-Item -ItemType Directory -Path $dstClean -Force | Out-Null } catch {} } $roboSrc = if ($srcClean -match '^[A-Za-z]:$') { "$srcClean\." } else { $srcClean } Write-RunnerLog " -> Backup Incremental [$srcClean] -> [$dstClean]..." "White" $modeFlags = if ($cfg.Modo -eq 'MIRROR') { @('/MIR') } else { @('/E', '/XO') } $excludeFiles = @('~$*', '*.tmp', '*.temp', '*.lock', '*.ldb', 'Thumbs.db', 'desktop.ini', 'pagefile.sys', 'hiberfil.sys', 'swapfile.sys') $roboArgs = @( "`"$roboSrc`"", "`"$dstClean`"" ) + $modeFlags + @( '/FFT', '/R:1', '/W:1', '/NP', '/NDL', '/XF' ) + $excludeFiles + @( '/XD' ) + $excludeArgs + @( "/LOG+:`"$logFile`"" ) $p = Start-Process -FilePath 'robocopy.exe' -ArgumentList ($roboArgs -join ' ') -NoNewWindow -PassThru -Wait $exitCode = $p.ExitCode try { & attrib.exe -H -S "$dstClean" 2>$null | Out-Null } catch {} if ($exitCode -ge 8) { $totalFailed++ Write-RunnerLog " [ALERTA] Robocopy devolveu codigo $exitCode em $srcClean" "Yellow" } elseif ($exitCode -ge 1) { $totalCopied++ } } if ($outlookWasRunning) { Write-RunnerLog "A reabrir o Microsoft Outlook em segundo plano..." "Cyan" try { Start-Process 'outlook.exe' } catch {} } $diskStats = Get-TargetDiskStats $destBase if ($null -ne $diskStats.UsedPct) { $diskLogMsg = "Espaco em disco de destino: $($diskStats.UsedPct)% ocupado ($($diskStats.FreeStr) livres de $($diskStats.TotalStr))." if ($diskStats.UsedPct -ge 92) { Write-RunnerLog "[ALERTA CRITICO DE DISCO] $diskLogMsg" "Red" } elseif ($diskStats.UsedPct -ge 85) { Write-RunnerLog "[AVISO DE DISCO] $diskLogMsg" "Yellow" } else { Write-RunnerLog $diskLogMsg "Green" } } # 5. Gerar Telemetria e Enviar Relatorio para backups@proservicecomputer.pt $endDt = Get-Date $duration = [Math]::Round(($endDt - $startDt).TotalSeconds, 1) $roboTotalFiles = 0 $roboCopiedFiles = 0 $roboFailedFiles = 0 $logTail = '' if (Test-Path $logFile) { try { $allLogLines = Get-Content $logFile -ErrorAction SilentlyContinue foreach ($ln in $allLogLines) { if ($ln -match '^\s*(?:Files|Ficheiros)\s*:\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)') { $roboTotalFiles += [int]$matches[1] $roboCopiedFiles += [int]$matches[2] $roboFailedFiles += [int]$matches[5] } } $logTail = (($allLogLines | Select-Object -Last 32) | ForEach-Object { [string]$_ }) -join "`r`n" } catch {} } $effectiveFailed = if ($roboTotalFiles -gt 0) { $roboFailedFiles } else { $totalFailed } $effectiveCopied = if ($roboTotalFiles -gt 0) { $roboCopiedFiles } else { $totalCopied } $finalState = 'SUCCESS' if ($totalFailed -gt 0 -and $roboTotalFiles -eq 0) { $finalState = 'FAILED' } elseif ($null -ne $diskStats.UsedPct -and $diskStats.UsedPct -ge 85) { $finalState = 'WARNING' } $msgResumo = "Backup Incremental (Sem Apagar no Destino) concluido com sucesso." if ($effectiveFailed -gt 0) { $msgResumo = "Concluido com $effectiveFailed ficheiro(s) em uso ($roboTotalFiles verificados, $effectiveCopied copiados)." } elseif ($roboTotalFiles -gt 0) { $msgResumo = "Backup concluido com sucesso ($roboTotalFiles ficheiros verificados, $effectiveCopied copiados)." } if ($null -ne $diskStats.UsedPct -and $diskStats.UsedPct -ge 85) { $msgResumo += " ATENCAO: Disco a $($diskStats.UsedPct)% de ocupacao!" } if ($alerta6Meses) { $msgResumo += " RECOMENDACAO: Disco com +6 meses de dados antigos (formatar)." } $cleanTail = ($logTail -replace '[\x00-\x08\x0B\x0C\x0E-\x1F]', '') $statusProps = @{ Cliente = [string]$cfg.Cliente Maquina = $env:COMPUTERNAME PlanoId = $cleanPlan Estado = $finalState Mensagem = $msgResumo Destino = $destBase EspacoLivreDestino = $diskStats.FreeStr EspacoTotalDestino = $diskStats.TotalStr OcupacaoPercent = $diskStats.UsedPct HorarioAgendado = [string]$cfg.Horario Periodicidade = [string]$cfg.Periodicidade Modo = [string]$cfg.Modo DataInicioCiclo = [string]$cfg.DataInicioCiclo DataProximaFormatacao6M = [string]$cfg.DataProximaFormatacao6M Alerta6Meses = [bool]$alerta6Meses EmailRelatorio = [string]$cfg.EmailRelatorio EnviarEmailRelatorio = [bool]$cfg.EnviarEmailRelatorio TotalFicheiros = [int]$roboTotalFiles FicheirosCopiados = [int]$effectiveCopied FicheirosFalhados = [int]$effectiveFailed DuracaoSegundos = $duration DataHora = $endDt.ToString('yyyy-MM-dd HH:mm:ss') PastasIncluidas = @($cfg.Origens) ResumoLog = $cleanTail ForceTelegramAlert = [bool]$ForceTelegram } $jsonStatus = '' try { Add-Type -AssemblyName System.Web.Extensions -ErrorAction Stop $jss = New-Object System.Web.Script.Serialization.JavaScriptSerializer $jss.MaxJsonLength = 8388608 $jsonStatus = $jss.Serialize($statusProps) } catch { $jsonStatus = (New-Object PSObject -Property $statusProps) | ConvertTo-Json -Depth 4 } if ([string]::IsNullOrWhiteSpace($jsonStatus) -or $jsonStatus.Length -lt 20) { $statusProps.ResumoLog = '' try { $jsonStatus = $jss.Serialize($statusProps) } catch { $jsonStatus = (New-Object PSObject -Property $statusProps) | ConvertTo-Json -Depth 4 } } $encNoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($statusFile, $jsonStatus, $encNoBom) try { [System.IO.File]::WriteAllText((Join-Path $destBase ".last_backup_$($env:COMPUTERNAME)$planSuffix.json"), $jsonStatus, $encNoBom) } catch {} Write-RunnerLog "[5/5] A enviar Relatorio para $($cfg.EmailRelatorio) e Dashboard PSC..." "Cyan" try { $cleanClient = ($cfg.Cliente -replace '[^A-Za-z0-9_-]', '_') $cleanHost = ($env:COMPUTERNAME -replace '[^A-Za-z0-9_-]', '_') $body = @{ token = $token host = $env:COMPUTERNAME filename = "Backup-PSC_${cleanClient}_${cleanHost}.json" content = $jsonStatus } $resp = Invoke-RestMethod -Uri $portalUrl -Method Post -Body $body -TimeoutSec 15 Write-RunnerLog "Relatorio enviado para $($cfg.EmailRelatorio) (MailOK: $($resp.mail_report_sent))!" "Green" } catch { Write-RunnerLog "[AVISO] Nao foi possivel contactar o Portal PSC online: $_" "Yellow" } Write-RunnerLog "==========================================================" "Green" Write-RunnerLog " BACKUP FINALIZADO EM ${duration}s | ESTADO: $finalState" "Green" Write-RunnerLog "==========================================================" "Green" try { if (Test-Path $lockFile) { Remove-Item $lockFile -Force -ErrorAction SilentlyContinue } } catch {} '@ $runnerCode | Set-Content -Path $Global:PSCRunnerFile -Encoding UTF8 } function Register-PSCBackupTask([string]$horario, [string]$periodicidade = 'DIARIO', [string]$diaSemana = 'Monday', [string]$planId = 'PRINCIPAL') { Build-PSCRunnerScript $pPaths = Get-PSCPlanPaths $planId Unregister-ScheduledTask -TaskName $pPaths.TaskName -Confirm:$false -ErrorAction SilentlyContinue $runnerArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$Global:PSCRunnerFile`"" if (-not $pPaths.IsDefault) { $runnerArgs += " -PlanId `"$($pPaths.PlanId)`"" } $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $runnerArgs if ($periodicidade -eq 'DIAS_UTEIS') { $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday,Tuesday,Wednesday,Thursday,Friday -At $horario } elseif ($periodicidade -eq 'SEMANAL') { $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek $diaSemana -At $horario } else { $trigger = New-ScheduledTaskTrigger -Daily -At $horario } $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest try { Register-ScheduledTask -TaskName $pPaths.TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description "PSC Enterprise Backup Engine [$($pPaths.PlanId)] ($periodicidade as $horario)" -Force | Out-Null Write-Host " [OK] Tarefa Agendada '$($pPaths.TaskName)' registada ($periodicidade as $horario como SYSTEM)!" -ForegroundColor Green return $true } catch { Write-Host " [ERRO] Falha ao registar Tarefa Agendada: $_" -ForegroundColor Red return $false } } function Invoke-PSCSetupWizard { Write-PSCServerHeader Write-Host "`n [1] ASSISTENTE DE CONFIGURACAO DE BACKUP (SERVIDORES DE CLIENTES)" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray $existingPlans = @(Get-PSCAllPlans) $planId = 'PRINCIPAL' $defaultClient = $env:COMPUTERNAME if ($existingPlans.Count -gt 0) { if ($existingPlans[0].Config.Cliente) { $defaultClient = [string]$existingPlans[0].Config.Cliente } Write-Host "`n Ja existem $($existingPlans.Count) plano(s) configurado(s) neste servidor:" -ForegroundColor Cyan foreach ($ep in $existingPlans) { Write-Host (" - {0,-14} -> {1} ({2} as {3})" -f $ep.Paths.PlanId, $ep.Config.DestinoBase, $ep.Config.Periodicidade, $ep.Config.Horario) -ForegroundColor Gray } $planChoice = (Read-Host "`n Deseja criar um NOVO plano adicional (ex: DIARIOS_2)? (Enter = S / N para substituir PRINCIPAL)").Trim() if ($planChoice -notmatch '^[nN]') { $suggestedName = "DIARIOS_" + ($existingPlans.Count + 1) $inpPlan = (Read-Host " Nome do Novo Plano (sem espacos, ex: DIARIOS_2 | Enter para '$suggestedName')").Trim() if ([string]::IsNullOrWhiteSpace($inpPlan)) { $inpPlan = $suggestedName } $planId = ($inpPlan -replace '[^A-Za-z0-9_-]', '_').Trim('_') if ([string]::IsNullOrWhiteSpace($planId)) { $planId = $suggestedName } } } $cliente = Read-Host " 1. Nome do Cliente / Empresa (Enter para '$defaultClient')" if ([string]::IsNullOrWhiteSpace($cliente)) { $cliente = $defaultClient } Write-Host "`n 2. Tipo de Disco / Destino do Backup:" -ForegroundColor Cyan Write-Host " [1] Disco Local / Externo USB / Unidade Dedicada (ex: E:\PSC_BACKUPS, D:\Backups)" -ForegroundColor White Write-Host " [2] NAS / Partilha de Rede SMB (ex: \\NAS-CLIENTE\Backups)" -ForegroundColor White $tipoOpt = Read-Host " Escolha (Enter para 1 - Disco Local/USB, ou 2 para NAS)" $tipoDestino = 'LOCAL' $nasHost = '' $nasIpFallback = '' $nasSharePath = '' $nasUser = '' $nasPass = '' $destinoBase = '' if ($tipoOpt -eq '2') { $tipoDestino = 'SMB' $nasHost = Read-Host " Hostname ou IP principal do NAS (ex: NAS-CLIENTE ou MyCloud-PKK1ET)" $nasIpFallback= Read-Host " IP de Fallback caso o DNS falhe (opcional, ex: 192.168.1.69)" $nasSharePath = Read-Host " Partilha e Pasta no NAS (sem barras iniciais, ex: Backups\DIARIO)" $nasSharePath = $nasSharePath.TrimStart('\') $nasUser = Read-Host " Utilizador SMB do NAS (deixe vazio se publico)" if (-not [string]::IsNullOrWhiteSpace($nasUser)) { $nasPass = Read-Host " Password SMB do NAS" } $destinoBase = "\\$nasHost\$nasSharePath" Write-Host "`n A testar ligacao SMB a $destinoBase..." -ForegroundColor Cyan try { net use "\\$nasHost\IPC$" /delete /y 2>$null | Out-Null if ($nasUser -and $nasPass) { $null = net use "\\$nasHost\IPC$" $nasPass /user:$nasUser 2>&1 } if (-not (Test-Path $destinoBase)) { New-Item -ItemType Directory -Path $destinoBase -Force -ErrorAction SilentlyContinue | Out-Null } if (Test-Path $destinoBase) { Write-Host " [OK] Ligacao e permissoes confirmadas em $destinoBase!" -ForegroundColor Green } else { Write-Host " [AVISO] Nao foi possivel validar $destinoBase agora, mas a configuracao sera guardada." -ForegroundColor Yellow } } catch { Write-Host " [AVISO] Erro ao testar ligacao: $_" -ForegroundColor Yellow } } else { $tipoDestino = 'LOCAL' $destinoBase = (Read-Host " Caminho do Disco/Pasta de Destino (ex: E:\PSC_BACKUPS)").Trim() if ($destinoBase -match '^[A-Za-z]:$') { $destinoBase = "$destinoBase\" } if (-not (Test-Path $destinoBase)) { try { New-Item -ItemType Directory -Path $destinoBase -Force | Out-Null Write-Host " [OK] Pasta criada em $destinoBase!" -ForegroundColor Green } catch { Write-Host " [AVISO] Nao foi possivel criar a pasta agora: $_" -ForegroundColor Yellow } } } $origens = New-Object System.Collections.Generic.List[string] $fecharOutlook = $false while ($true) { Write-Host "`n 3. Selecionar Pastas de Origem a incluir no Backup:" -ForegroundColor Cyan if ($origens.Count -gt 0) { Write-Host " Pastas ja selecionadas:" -ForegroundColor Green foreach ($o in $origens) { Write-Host " + $o" -ForegroundColor Gray } } Write-Host " [A] Introduzir pasta de Servidor/Dados (ex: D:\DADOS, C:\PHC, C:\Sage, C:\SQL_Backups)" -ForegroundColor White Write-Host " [B] Adicionar Pastas do Utilizador Atual (Desktop, Documents, Downloads, Pictures)" -ForegroundColor White Write-Host " [C] Adicionar Pasta de PSTs do Outlook + Ativar Fecho/Reabertura Automatica" -ForegroundColor White Write-Host " [D] Adicionar Raiz C:\PSC-ANTIGRAVITY" -ForegroundColor White Write-Host " [0] Concluir selecao de pastas e avancar" -ForegroundColor Yellow $pOpt = (Read-Host " Opcao").ToUpper() if ($pOpt -eq '0' -or $pOpt -eq '') { if ($origens.Count -eq 0) { Write-Host " [!] Selecione pelo menos uma pasta de origem." -ForegroundColor Red continue } break } elseif ($pOpt -eq 'A') { $customPath = Read-Host " Introduza o caminho completo da pasta (ex: D:\Partilha_Empresa)" if (-not [string]::IsNullOrWhiteSpace($customPath)) { if (-not $origens.Contains($customPath)) { $origens.Add($customPath) Write-Host " [OK] Pasta adicionada: $customPath" -ForegroundColor Green } } } elseif ($pOpt -eq 'B') { foreach ($sub in @('Desktop', 'Documents', 'Downloads', 'Pictures', '.ssh')) { $cand = Join-Path $env:USERPROFILE $sub if ((Test-Path $cand) -and (-not $origens.Contains($cand))) { $origens.Add($cand) } } Write-Host " [OK] Pastas do perfil de utilizador adicionadas!" -ForegroundColor Green } elseif ($pOpt -eq 'C') { $defaultOl = Join-Path $env:USERPROFILE 'OUTLOOK' if (-not (Test-Path $defaultOl)) { $altOl = Join-Path $env:USERPROFILE 'Documents\Ficheiros do Outlook' if (Test-Path $altOl) { $defaultOl = $altOl } } $olCustom = Read-Host " Caminho da pasta do Outlook (Enter para '$defaultOl')" if ([string]::IsNullOrWhiteSpace($olCustom)) { $olCustom = $defaultOl } if (-not $origens.Contains($olCustom)) { $origens.Add($olCustom) } $fecharOutlook = $true Write-Host " [OK] Pasta Outlook adicionada e fecho/reabertura automatica ativado!" -ForegroundColor Green } elseif ($pOpt -eq 'D') { if (-not $origens.Contains('C:\PSC-ANTIGRAVITY')) { $origens.Add('C:\PSC-ANTIGRAVITY') } Write-Host " [OK] C:\PSC-ANTIGRAVITY adicionado!" -ForegroundColor Green } } Write-Host "`n 4. Modo de Backup (Politica de Retencao no Destino):" -ForegroundColor Cyan Write-Host " [1] INCREMENTAL SEM APAGAR (Padrao Servidores PSC: se o cliente apagar na origem, o destino MANTEM)" -ForegroundColor Green Write-Host " [2] ESPELHO PURO /MIR (Iguala o destino a origem)" -ForegroundColor White $mOpt = Read-Host " Escolha (Enter para 1 - INCREMENTAL SEM APAGAR)" $modo = if ($mOpt -eq '2') { 'MIRROR' } else { 'INCREMENTAL_SEM_APAGAR' } Write-Host "`n 5. Horario e Periodicidade (Padrao Servidores: 00:01 e Diario):" -ForegroundColor Cyan Write-Host " [1] DIARIO (Todos os dias)" -ForegroundColor Green Write-Host " [2] DIAS UTEIS (Segunda a Sexta)" -ForegroundColor White Write-Host " [3] SEMANAL (1 vez por semana)" -ForegroundColor White $perOpt = Read-Host " Periodicidade (Enter para 1 - DIARIO)" $periodicidade = if ($perOpt -eq '2') { 'DIAS_UTEIS' } elseif ($perOpt -eq '3') { 'SEMANAL' } else { 'DIARIO' } $horario = Read-Host " Hora de execucao no formato HH:mm (Enter para '00:01')" if ([string]::IsNullOrWhiteSpace($horario)) { $horario = '00:01' } Write-Host "`n 6. Aviso Semestral (6 em 6 Meses) & Relatorio para backups@proservicecomputer.pt:" -ForegroundColor Cyan $rot6Opt = Read-Host " Enviar alerta de recomendacao de formatacao ao fim de 6 meses? (Enter = S / N)" $ativarRot6M = ($rot6Opt -notmatch '^[nN]') $dataInicioCiclo = (Get-Date).ToString('yyyy-MM-dd') $dataProx6M = (Get-Date).AddMonths(6).ToString('yyyy-MM-dd') $emailRel = Read-Host " Email para Relatorios e Alertas (Enter para 'backups@proservicecomputer.pt')" if ([string]::IsNullOrWhiteSpace($emailRel)) { $emailRel = 'backups@proservicecomputer.pt' } $cfgObj = [PSCustomObject]@{ Cliente = $cliente Maquina = $env:COMPUTERNAME TipoDestino = $tipoDestino DestinoBase = $destinoBase NasHost = $nasHost NasIpFallback = $nasIpFallback NasSharePath = $nasSharePath NasUser = $nasUser NasPass = $nasPass Origens = $origens.ToArray() FecharOutlook = $fecharOutlook Modo = $modo Periodicidade = $periodicidade Horario = $horario AtivarRotacao6Meses = $ativarRot6M DataInicioCiclo = $dataInicioCiclo DataProximaFormatacao6M = $dataProx6M EmailRelatorio = $emailRel EnviarEmailRelatorio = $true CriadoEm = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') } Save-PSCBackupConfig $cfgObj $planId Register-PSCBackupTask -horario $horario -periodicidade $periodicidade -planId $planId | Out-Null Write-Host "`n ================================================================" -ForegroundColor Green Write-Host " PLANO DE BACKUP [$planId] CONFIGURADO COM SUCESSO!" -ForegroundColor Green Write-Host " - Modo : $modo (Nao apaga ficheiros eliminados na origem)" -ForegroundColor White Write-Host " - Horario : $horario ($periodicidade)" -ForegroundColor White Write-Host " - Relatorio Mail : $emailRel (inclui % ocupacao do disco)" -ForegroundColor White Write-Host " - Aviso 6 Meses : Recomendacao de formatacao em $dataProx6M (sem apagar auto)" -ForegroundColor Yellow Write-Host " ================================================================" -ForegroundColor Green $runNow = Read-Host "`n Deseja executar o 1.o backup de teste deste plano agora e enviar relatorio para $emailRel? (S/N)" if ($runNow -match '^[sS]') { & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Global:PSCRunnerFile -PlanId $planId -ForceTelegram } Read-Host "`n Prima Enter para voltar" } function Invoke-PSCManageFolders { $selPlan = Select-PSCPlan "SELECIONE O PLANO A GERIR:" if (-not $selPlan) { Write-Host "`n [!] Nenhum plano configurado. Execute primeiro a opcao [1]." -ForegroundColor Yellow Read-Host " Prima Enter para continuar" return } $planId = $selPlan.Paths.PlanId $cfg = $selPlan.Config while ($true) { Write-PSCServerHeader Write-Host "`n GERIR PLANO [$planId] - PASTAS DE ORIGEM, HORARIO & OUTLOOK" -ForegroundColor Yellow $list = New-Object System.Collections.Generic.List[string] foreach ($item in @($cfg.Origens)) { $list.Add([string]$item) } for ($i = 0; $i -lt $list.Count; $i++) { Write-Host (" [{0}] {1}" -f ($i + 1), $list[$i]) -ForegroundColor White } Write-Host ("`n Modo Atual : {0}" -f $cfg.Modo) -ForegroundColor Green Write-Host (" Horario / Periodo : {0} ({1})" -f $cfg.Horario, $cfg.Periodicidade) -ForegroundColor Cyan Write-Host (" Fecho Suave Outlook : {0}" -f $cfg.FecharOutlook) -ForegroundColor Cyan Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " [A] Adicionar nova pasta de origem" -ForegroundColor Green Write-Host " [R] Remover uma pasta pelo numero" -ForegroundColor Yellow Write-Host " [H] Alterar Horario / Periodicidade (ex: 00:01 Diario)" -ForegroundColor Cyan Write-Host " [M] Alternar Modo (INCREMENTAL_SEM_APAGAR <-> MIRROR)" -ForegroundColor Cyan Write-Host " [O] Alternar Fecho Automatico do Outlook (True/False)" -ForegroundColor Cyan Write-Host " [0] Guardar e Voltar" -ForegroundColor Gray $op = (Read-Host "`n Opcao").ToUpper() if ($op -eq '0' -or $op -eq '') { break } elseif ($op -eq 'A') { $np = Read-Host " Caminho completo da nova pasta" if (-not [string]::IsNullOrWhiteSpace($np) -and (-not $list.Contains($np))) { $list.Add($np) $cfg.Origens = $list.ToArray() Save-PSCBackupConfig $cfg $planId Build-PSCRunnerScript } } elseif ($op -eq 'R') { $idxStr = Read-Host " Numero da pasta a remover" $idx = 0 if ([int]::TryParse($idxStr, [ref]$idx) -and $idx -ge 1 -and $idx -le $list.Count) { $list.RemoveAt($idx - 1) $cfg.Origens = $list.ToArray() Save-PSCBackupConfig $cfg $planId Build-PSCRunnerScript } } elseif ($op -eq 'H') { $nh = Read-Host " Novo Horario HH:mm (Enter para '00:01')" if ([string]::IsNullOrWhiteSpace($nh)) { $nh = '00:01' } $cfg.Horario = $nh Save-PSCBackupConfig $cfg $planId Register-PSCBackupTask -horario $cfg.Horario -periodicidade $cfg.Periodicidade -planId $planId | Out-Null } elseif ($op -eq 'M') { $cfg.Modo = if ($cfg.Modo -eq 'MIRROR') { 'INCREMENTAL_SEM_APAGAR' } else { 'MIRROR' } Save-PSCBackupConfig $cfg $planId Build-PSCRunnerScript } elseif ($op -eq 'O') { $cfg.FecharOutlook = -not [bool]$cfg.FecharOutlook Save-PSCBackupConfig $cfg $planId Build-PSCRunnerScript } } } function Invoke-PSCSixMonthManager { $selPlan = Select-PSCPlan "SELECIONE O PLANO (AVISO 6 MESES):" if (-not $selPlan) { Write-Host "`n [!] Configure primeiro o plano na opcao [1]." -ForegroundColor Yellow Read-Host " Prima Enter para voltar" return } $planId = $selPlan.Paths.PlanId $cfg = $selPlan.Config Write-PSCServerHeader Write-Host "`n GESTAO DO AVISO SEMESTRAL [$planId] (6 EM 6 MESES - HUMAN-IN-THE-LOOP)" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " Inicio do Ciclo Atual : $($cfg.DataInicioCiclo)" -ForegroundColor White Write-Host " Data do Aviso de 6 Meses : $($cfg.DataProximaFormatacao6M)" -ForegroundColor Green Write-Host " Email de Destino do Aviso : $($cfg.EmailRelatorio)" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " [1] Ja formatei/limpei o disco hoje -> Reiniciar contador para +6 meses" -ForegroundColor Green Write-Host " [2] Testar agora o envio do Aviso de 6 Meses para $($cfg.EmailRelatorio)" -ForegroundColor Cyan Write-Host " [0] Voltar" -ForegroundColor Gray $cOpt = Read-Host "`n Escolha" if ($cOpt -eq '1') { $cfg.DataInicioCiclo = (Get-Date).ToString('yyyy-MM-dd') $cfg.DataProximaFormatacao6M = (Get-Date).AddMonths(6).ToString('yyyy-MM-dd') Save-PSCBackupConfig $cfg $planId Write-Host " [OK] Contador [$planId] reiniciado! Proxima recomendacao em $($cfg.DataProximaFormatacao6M)." -ForegroundColor Green Read-Host " Prima Enter para continuar" } elseif ($cOpt -eq '2') { if (-not (Test-Path $Global:PSCRunnerFile)) { Build-PSCRunnerScript } & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Global:PSCRunnerFile -PlanId $planId -TestSixMonthAlert -ForceTelegram Read-Host "`n Prima Enter para voltar" } } function Invoke-PSCTestDestination { Write-PSCServerHeader Write-Host "`n DIAGNOSTICO DE LIGACAO AO DISCO / NAS & VELOCIDADE" -ForegroundColor Yellow $selPlan = Select-PSCPlan "SELECIONE O PLANO A TESTAR:" if (-not $selPlan) { Write-Host " [!] Configure primeiro o plano na opcao [1]." -ForegroundColor Yellow Read-Host " Prima Enter para voltar" return } $cfg = $selPlan.Config $dest = $cfg.DestinoBase if ($cfg.TipoDestino -eq 'SMB') { Write-Host " A testar resolucao DNS/NetBIOS de '$($cfg.NasHost)'..." -ForegroundColor Cyan try { $ips = [System.Net.Dns]::GetHostAddresses($cfg.NasHost) | Select-Object -ExpandProperty IPAddressToString Write-Host " [OK] Hostname resolvido para IP: $($ips -join ', ')" -ForegroundColor Green } catch { Write-Host " [AVISO] Falha ao resolver hostname '$($cfg.NasHost)'." -ForegroundColor Yellow } Write-Host " A autenticar sessao SMB..." -ForegroundColor Cyan net use "\\$($cfg.NasHost)\IPC$" /delete /y 2>$null | Out-Null if ($cfg.NasUser -and $cfg.NasPass) { $null = net use "\\$($cfg.NasHost)\IPC$" $cfg.NasPass /user:$cfg.NasUser 2>&1 } } if (Test-Path $dest) { Write-Host " [OK] Destino acessivel: $dest" -ForegroundColor Green $testFile = Join-Path $dest "psc_speedtest_$($env:COMPUTERNAME).tmp" Write-Host " A efetuar teste de escrita (4 MB)..." -ForegroundColor Cyan try { $bytes = New-Object byte[] (4 * 1024 * 1024) $sw = [System.Diagnostics.Stopwatch]::StartNew() [System.IO.File]::WriteAllBytes($testFile, $bytes) $sw.Stop() Remove-Item $testFile -Force -ErrorAction SilentlyContinue $mbps = [Math]::Round(4.0 / [Math]::Max(0.05, $sw.Elapsed.TotalSeconds), 2) Write-Host " [OK] Escrita verificada com sucesso! Velocidade media: $mbps MB/s" -ForegroundColor Green } catch { Write-Host " [ERRO] Falha ao escrever no destino: $_" -ForegroundColor Red } } else { Write-Host " [ERRO] O caminho '$dest' nao esta acessivel!" -ForegroundColor Red } Read-Host "`n Prima Enter para voltar" } function Show-PSCBackupSubMenu { while ($true) { Write-PSCServerHeader Write-Host "`n [1] CENTRAL DE BACKUPS DE SERVIDOR (SUBSTITUTO COBIAN)" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " [1] Assistente de Configuracao Inicial (00h01 / Incremental Sem Apagar)" -ForegroundColor White Write-Host " [2] Executar Backup Agora (Teste Manual + Enviar Relatorio p/ backups@proservicecomputer.pt)" -ForegroundColor Green Write-Host " [3] Ver Estado da Tarefa Agendada & Ultimas Linhas do Log" -ForegroundColor White Write-Host " [4] Gerir Pastas de Origem, Horario (00:01) & Protecao Outlook (PST)" -ForegroundColor White Write-Host " [5] Diagnosticar Ligacao ao Disco / NAS & Velocidade de Escrita" -ForegroundColor White Write-Host " [6] Aviso Semestral 6 Meses (Reiniciar Contador apos Formatacao Manual)" -ForegroundColor Yellow Write-Host " [7] Remover / Desativar Tarefa Agendada de Backup" -ForegroundColor DarkYellow Write-Host " [0] Voltar ao Menu Principal" -ForegroundColor Gray $bOpt = Read-Host "`n Escolha" switch ($bOpt) { '1' { Invoke-PSCSetupWizard } '2' { $sel = Select-PSCPlan "SELECIONE O PLANO A EXECUTAR AGORA:" if ($sel) { if (-not (Test-Path $Global:PSCRunnerFile)) { Build-PSCRunnerScript } Write-Host "`n A iniciar execucao manual do plano [$($sel.Paths.PlanId)]..." -ForegroundColor Cyan & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Global:PSCRunnerFile -PlanId $sel.Paths.PlanId -ForceTelegram } else { Write-Host "`n [!] Nenhum plano configurado." -ForegroundColor Yellow } Read-Host "`n Prima Enter para voltar" } '3' { $sel = Select-PSCPlan "SELECIONE O PLANO PARA VER LOGS:" Write-PSCServerHeader if ($sel) { Write-Host "`n ESTADO DA TAREFA [$($sel.Paths.PlanId)] & ULTIMOS LOGS" -ForegroundColor Yellow Get-ScheduledTask -TaskName $sel.Paths.TaskName -ErrorAction SilentlyContinue | Format-List TaskName, State, Description Get-ScheduledTaskInfo -TaskName $sel.Paths.TaskName -ErrorAction SilentlyContinue | Format-List LastRunTime, NextRunTime, LastTaskResult if (Test-Path $sel.Paths.LogFile) { Write-Host " --- Ultimas 30 linhas de $($sel.Paths.LogFile) ---" -ForegroundColor Cyan Get-Content $sel.Paths.LogFile -Tail 30 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray } } else { Write-Host " Ainda nao existe ficheiro de log em $($sel.Paths.LogFile)." -ForegroundColor Yellow } } else { Write-Host "`n [!] Nenhum plano configurado." -ForegroundColor Yellow } Read-Host "`n Prima Enter para voltar" } '4' { Invoke-PSCManageFolders } '5' { Invoke-PSCTestDestination } '6' { Invoke-PSCSixMonthManager } '7' { $sel = Select-PSCPlan "SELECIONE O PLANO A REMOVER:" if ($sel) { $confirm = Read-Host "`n Tem a certeza que deseja remover a Tarefa Agendada '$($sel.Paths.TaskName)'? (S/N)" if ($confirm -match '^[sS]') { Unregister-ScheduledTask -TaskName $sel.Paths.TaskName -Confirm:$false -ErrorAction SilentlyContinue if (-not $sel.Paths.IsDefault -and (Test-Path $sel.Paths.ConfigFile)) { Remove-Item $sel.Paths.ConfigFile -Force -ErrorAction SilentlyContinue } Write-Host " [OK] Tarefa/Plano [$($sel.Paths.PlanId)] removido." -ForegroundColor Yellow Start-Sleep -Seconds 2 } } } '0' { return } } } } # ============================================================================ # MODULO 2: CENTRAL VPN SERVIDOR (RRAS SSTP + WATCHDOG 5 MIN) # ============================================================================ function Install-PSCServerSstpRras { Write-PSCServerHeader Write-Host "`n CONFIGURAR SERVIDOR VPN SSTP (WINDOWS SERVER RRAS)" -ForegroundColor Yellow Write-Host " Gera certificado SSL 5 anos, regista na Raiz do Servidor, exporta C:\CERT\sstp_public.cer e vincula ao RRAS." -ForegroundColor Gray $vpnHost = (Read-Host "`n Hostname / DynDNS publico do Servidor (ex: pateopetisco.dyndns.org)").Trim() if ([string]::IsNullOrWhiteSpace($vpnHost)) { Write-Host " [!] O Hostname / DynDNS e obrigatorio." -ForegroundColor Yellow Read-Host " Prima Enter para voltar" return } $certFolder = 'C:\CERT' if (-not (Test-Path $certFolder)) { New-Item -Path $certFolder -ItemType Directory -Force | Out-Null } $certPath = Join-Path $certFolder 'sstp_public.cer' Write-Host " [1/5] A gerar certificado SSL para '$vpnHost' (validade: 5 anos)..." -ForegroundColor Cyan try { $hasModernCertCmd = $false $nscCmd = Get-Command New-SelfSignedCertificate -ErrorAction SilentlyContinue if ($nscCmd -and $nscCmd.Parameters.ContainsKey('KeyExportPolicy')) { $hasModernCertCmd = $true } if ($hasModernCertCmd) { $cert = New-SelfSignedCertificate -DnsName $vpnHost -CertStoreLocation 'Cert:\LocalMachine\My' -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -HashAlgorithm SHA256 -NotAfter (Get-Date).AddYears(5) -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.1') -ErrorAction Stop } else { Write-Host " [INFO] PowerShell 4.0 / Server 2012 R2 detetado: a usar CertEnroll COM..." -ForegroundColor Gray $dn = New-Object -ComObject X509Enrollment.CX500DistinguishedName $dn.Encode("CN=$vpnHost", 0) $privKey = New-Object -ComObject X509Enrollment.CX509PrivateKey $privKey.ProviderName = 'Microsoft RSA SChannel Cryptographic Provider' $privKey.KeySpec = 1 $privKey.Length = 2048 $privKey.MachineContext = $true $privKey.ExportPolicy = 1 $privKey.Create() $oid = New-Object -ComObject X509Enrollment.CObjectId $oid.InitializeFromValue('1.3.6.1.5.5.7.3.1') $oids = New-Object -ComObject X509Enrollment.CObjectIds $oids.Add($oid) $eku = New-Object -ComObject X509Enrollment.CX509ExtensionEnhancedKeyUsage $eku.InitializeEncode($oids) $altName = New-Object -ComObject X509Enrollment.CAlternativeName $altName.InitializeFromString(3, $vpnHost) $altNames = New-Object -ComObject X509Enrollment.CAlternativeNames $altNames.Add($altName) $san = New-Object -ComObject X509Enrollment.CX509ExtensionAlternativeNames $san.InitializeEncode($altNames) $hashAlg = New-Object -ComObject X509Enrollment.CObjectId $hashAlg.InitializeFromAlgorithmName(1, 0, 0, 'SHA256') $req = New-Object -ComObject X509Enrollment.CX509CertificateRequestCertificate $req.InitializeFromPrivateKey(2, $privKey, '') $req.Subject = $dn $req.Issuer = $dn $req.NotBefore = (Get-Date).AddDays(-1) $req.NotAfter = (Get-Date).AddYears(5) $req.HashAlgorithm = $hashAlg $req.X509Extensions.Add($eku) $req.X509Extensions.Add($san) $req.Encode() $enroll = New-Object -ComObject X509Enrollment.CX509Enrollment $enroll.InitializeFromRequest($req) $enroll.CertificateFriendlyName = "PSC SSTP VPN ($vpnHost)" $certData = $enroll.CreateRequest(0) $enroll.InstallResponse(2, $certData, 0, '') $cert = Get-ChildItem 'Cert:\LocalMachine\My' | Where-Object { $_.Subject -eq "CN=$vpnHost" } | Sort-Object NotAfter -Descending | Select-Object -First 1 if (-not $cert) { throw "Certificado gerado mas nao encontrado em Cert:\LocalMachine\My." } } Export-Certificate -Cert $cert -FilePath $certPath -Force | Out-Null Import-Certificate -FilePath $certPath -CertStoreLocation 'Cert:\LocalMachine\Root' | Out-Null Write-Host " [OK] Certificado gerado (Thumbprint: $($cert.Thumbprint)) e exportado para $certPath" -ForegroundColor Green Write-Host " [2/5] A aplicar NoCertRevocationCheck = 1 e vincular Hash SHA-256 ao RRAS SSTP..." -ForegroundColor Cyan $sstpKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SstpSvc\Parameters' if (-not (Test-Path $sstpKey)) { New-Item -Path $sstpKey -Force | Out-Null } New-ItemProperty -Path $sstpKey -Name 'NoCertRevocationCheck' -Value 1 -PropertyType DWord -Force | Out-Null $rrasSstpKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\RemoteAccess\Parameters\SstpSvc' if (-not (Test-Path $rrasSstpKey)) { New-Item -Path $rrasSstpKey -Force | Out-Null } $sha256 = [System.Security.Cryptography.SHA256]::Create() $hashBytes = $sha256.ComputeHash($cert.RawData) Set-ItemProperty -Path $rrasSstpKey -Name 'Sha256CertificateHash' -Value $hashBytes -ErrorAction SilentlyContinue if (Get-Command Set-RemoteAccess -ErrorAction SilentlyContinue) { try { Set-RemoteAccess -SslCertificate $cert -ErrorAction SilentlyContinue } catch {} } Write-Host " [3/5] A vincular certificado na porta 443 (netsh http sslcert) e abrir Firewall..." -ForegroundColor Cyan $null = netsh http delete sslcert ipport=0.0.0.0:443 2>&1 $null = netsh http delete sslcert ipport=[::]:443 2>&1 $null = netsh http add sslcert ipport=0.0.0.0:443 certhash=$($cert.Thumbprint) appid="{ba195980-cd49-458b-9e23-c84ee0adcd75}" certstorename=MY 2>&1 $null = netsh http add sslcert ipport=[::]:443 certhash=$($cert.Thumbprint) appid="{ba195980-cd49-458b-9e23-c84ee0adcd75}" certstorename=MY 2>&1 if (Get-Command Get-NetFirewallRule -ErrorAction SilentlyContinue) { if (-not (Get-NetFirewallRule -DisplayName 'PSC-VPN-SSTP-443' -ErrorAction SilentlyContinue)) { New-NetFirewallRule -DisplayName 'PSC-VPN-SSTP-443' -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow -Profile Any -ErrorAction SilentlyContinue | Out-Null } else { Enable-NetFirewallRule -DisplayName 'PSC-VPN-SSTP-443' -ErrorAction SilentlyContinue } } Write-Host " [4/5] A ativar arranque automatico e reiniciar servicos SstpSvc e RemoteAccess..." -ForegroundColor Cyan Set-Service -Name SstpSvc -StartupType Automatic -ErrorAction SilentlyContinue Restart-Service SstpSvc -Force -ErrorAction SilentlyContinue Restart-Service RemoteAccess -Force -ErrorAction SilentlyContinue Write-Host " [OK] Servidor RRAS SSTP configurado para '$vpnHost' e certificado gravado em C:\CERT\sstp_public.cer!" -ForegroundColor Green } catch { Write-Host " [ERRO] Falha ao configurar certificado SSTP: $_" -ForegroundColor Red } Read-Host "`n Prima Enter para continuar" } function Install-PSCVpnWatchdogServer { Write-PSCServerHeader Write-Host "`n WATCHDOG VPN SEMPRE ATIVA (SERVIDOR RRAS / SSTP / SOFTETHER / OPENVPN)" -ForegroundColor Yellow Write-Host " Garante que os servicos VPN nunca ficam desligados apos reboots, updates ou quedas." -ForegroundColor Gray $candidates = @('RemoteAccess', 'SstpSvc', 'RasMan', 'IKEEXT', 'SEVPNSERVER', 'SEVPNCLIENT', 'OpenVPNService', 'OpenVPNServiceInteractive') $foundSvcs = @() foreach ($c in $candidates) { $s = Get-Service -Name $c -ErrorAction SilentlyContinue if ($s) { $foundSvcs += $s } } $wgSvcs = Get-Service -Name 'WireGuardTunnel*' -ErrorAction SilentlyContinue if ($wgSvcs) { $foundSvcs += $wgSvcs } if ($foundSvcs.Count -gt 0) { Write-Host "`n Servicos VPN detetados neste servidor:" -ForegroundColor Cyan foreach ($fs in $foundSvcs) { $col = if ($fs.Status -eq 'Running') { 'Green' } else { 'Yellow' } Write-Host (" - {0,-28} [{1}] ({2})" -f $fs.Name, $fs.Status, $fs.DisplayName) -ForegroundColor $col } } $defaultList = if ($foundSvcs.Count -gt 0) { ($foundSvcs | Select-Object -ExpandProperty Name) -join ',' } else { 'RemoteAccess,SstpSvc,RasMan' } $svcInput = (Read-Host "`n Servicos a vigiar separados por virgula (Enter para '$defaultList')").Trim() if ([string]::IsNullOrWhiteSpace($svcInput)) { $svcInput = $defaultList } $targetSvcs = @($svcInput -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) Write-Host "`n [1/3] A aplicar Arranque Automatico e Recuperacao Nativa (sc.exe failure)..." -ForegroundColor Cyan foreach ($sn in $targetSvcs) { $svcObj = Get-Service -Name $sn -ErrorAction SilentlyContinue if ($svcObj) { try { Set-Service -Name $sn -StartupType Automatic -ErrorAction SilentlyContinue } catch {} $null = sc.exe failure "$sn" reset= 86400 actions= restart/5000/restart/10000/restart/30000 2>&1 $null = sc.exe failureflag "$sn" 1 2>&1 if ($svcObj.Status -ne 'Running') { Start-Service -Name $sn -ErrorAction SilentlyContinue } Write-Host " [OK] Protecao nativa aplicada a: $sn" -ForegroundColor Green } } Write-Host " [2/3] A gerar script autonomo C:\PSC-WATCHDOG\watchdog_vpn.ps1..." -ForegroundColor Cyan $svcArrayLiteral = ($targetSvcs | ForEach-Object { "'$_'" }) -join ', ' $vpnWatchScript = @" # PSC Watchdog VPN - Execucao automatica a cada 5 minutos (SYSTEM) `$ErrorActionPreference = 'SilentlyContinue' `$logFile = 'C:\PSC-WATCHDOG\vpn_watchdog.log' `$services = @($svcArrayLiteral) function Write-WLog([string]`$msg) { `$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' Add-Content -Path `$logFile -Value "[`$ts] `$msg" -Encoding UTF8 } if ((Test-Path `$logFile) -and ((Get-Item `$logFile).Length -gt 2MB)) { Move-Item `$logFile "`$logFile.old" -Force } foreach (`$sName in `$services) { `$s = Get-Service -Name `$sName if (-not `$s) { continue } if (`$s.StartType -eq 'Disabled') { Set-Service -Name `$sName -StartupType Automatic } if (`$s.Status -ne 'Running') { Write-WLog "ALERTA: Servico [`$sName] estava no estado [`$(`$s.Status)]. A iniciar..." Start-Service -Name `$sName Start-Sleep -Seconds 3 `$sAfter = Get-Service -Name `$sName Write-WLog "RESULTADO: Servico [`$sName] ficou no estado [`$(`$sAfter.Status)]." } } "@ $scriptPath = Join-Path $Global:PSCWatchdogDir 'watchdog_vpn.ps1' $vpnWatchScript | Set-Content -Path $scriptPath -Encoding ASCII Write-Host " [3/3] A registar Tarefa Agendada PSC_Watchdog_VPN (SYSTEM, a cada 5 minutos)..." -ForegroundColor Cyan $taskName = 'PSC_Watchdog_VPN' Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$scriptPath`"" $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650) $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 2) $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'PSC Watchdog: Garante servicos VPN sempre ativos (verifica a cada 5 min)' -Force | Out-Null & $scriptPath Write-Host "`n [OK] Watchdog VPN ativo! Tarefa '$taskName' a vigiar: $($targetSvcs -join ', ')." -ForegroundColor Green Read-Host " Prima Enter para voltar" } function Show-PSCVpnServerSubMenu { while ($true) { Write-PSCServerHeader Write-Host "`n [2] CENTRAL VPN SERVIDOR (RRAS SSTP & WATCHDOG 5 MIN)" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " [1] Configurar Servidor VPN SSTP (Gerar Certificado SSL 5 Anos + RRAS)" -ForegroundColor White Write-Host " [2] Ativar Watchdog VPN Sempre Ativa (Auto-restart servicos a cada 5 min)" -ForegroundColor Green Write-Host " [3] Ver Log do Watchdog VPN (C:\PSC-WATCHDOG\vpn_watchdog.log)" -ForegroundColor Cyan Write-Host " [4] Remover Tarefa Watchdog VPN" -ForegroundColor DarkYellow Write-Host " [0] Voltar ao Menu Principal" -ForegroundColor Gray $vOpt = Read-Host "`n Escolha" switch ($vOpt) { '1' { Install-PSCServerSstpRras } '2' { Install-PSCVpnWatchdogServer } '3' { $lf = 'C:\PSC-WATCHDOG\vpn_watchdog.log' if (Test-Path $lf) { Get-Content $lf -Tail 35 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray } } else { Write-Host " Sem incidentes registados (servicos VPN sempre ativos)." -ForegroundColor Green } Read-Host "`n Prima Enter para voltar" } '4' { Unregister-ScheduledTask -TaskName 'PSC_Watchdog_VPN' -Confirm:$false -ErrorAction SilentlyContinue Write-Host " [OK] Tarefa PSC_Watchdog_VPN removida." -ForegroundColor Yellow Start-Sleep -Seconds 2 } '0' { return } } } } # ============================================================================ # MODULO 3: WATCHDOG DYNDNS SEMPRE ATIVO (SERVICO LOCAL + HTTP NATIVO 10 MIN) # ============================================================================ function Install-PSCDynDnsWatchdogServer { Write-PSCServerHeader Write-Host "`n [3] WATCHDOG DYNDNS SEMPRE ATIVO (SERVICO LOCAL + ATUALIZADOR HTTP 10 MIN)" -ForegroundColor Yellow Write-Host " Mantem o DynDNS sempre atualizado mesmo sem sessao iniciada ou se a app oficial falhar." -ForegroundColor Gray $ddnsSvcs = @(Get-Service | Where-Object { $_.Name -match 'dyndns|noip|no-ip|duc|duckdns|ddns' -or $_.DisplayName -match 'DynDNS|No-IP|DuckDNS|DDNS' }) $svcNames = @() if ($ddnsSvcs.Count -gt 0) { Write-Host "`n Servicos DDNS locais detetados:" -ForegroundColor Cyan foreach ($ds in $ddnsSvcs) { Write-Host (" - {0,-28} [{1}] ({2})" -f $ds.Name, $ds.Status, $ds.DisplayName) -ForegroundColor Green $svcNames += $ds.Name try { Set-Service -Name $ds.Name -StartupType Automatic -ErrorAction SilentlyContinue } catch {} $null = sc.exe failure "$($ds.Name)" reset= 86400 actions= restart/5000/restart/10000/restart/30000 2>&1 if ($ds.Status -ne 'Running') { Start-Service -Name $ds.Name -ErrorAction SilentlyContinue } } } else { Write-Host "`n Nenhum servico DDNS local detetado (sera usado o Atualizador HTTP Nativo PSC)." -ForegroundColor Gray } Write-Host "`n Escolha o modo de atualizacao HTTP Nativa (independente de apps):" -ForegroundColor Cyan Write-Host " [1] DynDNS (members.dyndns.org) - Recomendado p/ DynDNS" -ForegroundColor White Write-Host " [2] No-IP (dynupdate.no-ip.com)" -ForegroundColor White Write-Host " [3] DuckDNS (www.duckdns.org)" -ForegroundColor White Write-Host " [4] Apenas vigiar o servico Windows local (sem HTTP)" -ForegroundColor Gray $provOpt = (Read-Host " Opcao (1-4)").Trim() $provider = 'SERVICE_ONLY' $ddnsHost = '' $ddnsUser = '' $ddnsPass = '' if ($provOpt -in @('1', '2', '3')) { $provider = switch ($provOpt) { '1' { 'DYNDNS' } '2' { 'NOIP' } '3' { 'DUCKDNS' } } $ddnsHost = (Read-Host " Hostname completo (ex: pateopetisco.dyndns.org ou subdominio DuckDNS)").Trim() if ($provOpt -eq '3') { $ddnsPass = (Read-Host " Token DuckDNS").Trim() } else { $ddnsUser = (Read-Host " Utilizador da conta DynDNS / No-IP").Trim() $ddnsPass = (Read-Host " Password / Updater Key").Trim() } } $cfgObj = [ordered]@{ Provider = $provider Hostname = $ddnsHost Username = $ddnsUser Secret = $ddnsPass Services = @($svcNames) } $cfgPath = Join-Path $Global:PSCWatchdogDir 'dyndns_config.json' $cfgObj | ConvertTo-Json -Depth 4 | Set-Content -Path $cfgPath -Encoding ASCII $dynWatchScript = @' # PSC Watchdog DynDNS - Execucao automatica a cada 10 minutos (SYSTEM) [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $ErrorActionPreference = 'SilentlyContinue' $logFile = 'C:\PSC-WATCHDOG\dyndns_watchdog.log' $cfgFile = 'C:\PSC-WATCHDOG\dyndns_config.json' $cacheFile = 'C:\PSC-WATCHDOG\dyndns_last_ip.txt' function Write-DLog([string]$msg) { $ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' Add-Content -Path $logFile -Value "[$ts] $msg" -Encoding UTF8 } if ((Test-Path $logFile) -and ((Get-Item $logFile).Length -gt 2MB)) { Move-Item $logFile "$logFile.old" -Force } if (-not (Test-Path $cfgFile)) { exit 0 } $cfg = Get-Content $cfgFile -Raw | ConvertFrom-Json foreach ($sName in @($cfg.Services)) { if ([string]::IsNullOrWhiteSpace($sName)) { continue } $s = Get-Service -Name $sName if ($s -and $s.Status -ne 'Running') { Write-DLog "ALERTA: Servico [$sName] parado. A iniciar..." Start-Service -Name $sName } } if ($cfg.Provider -eq 'SERVICE_ONLY' -or [string]::IsNullOrWhiteSpace($cfg.Hostname)) { exit 0 } $pubIp = '' foreach ($ipUrl in @('https://api.ipify.org', 'https://icanhazip.com', 'https://ifconfig.me/ip')) { try { $resp = (Invoke-RestMethod -Uri $ipUrl -TimeoutSec 10).Trim() if ($resp -match '^\d{1,3}(\.\d{1,3}){3}$') { $pubIp = $resp; break } } catch {} } if (-not $pubIp) { Write-DLog 'AVISO: Nao foi possivel obter IP publico atual.'; exit 0 } $lastIp = '' $forceKeepAlive = $false if (Test-Path $cacheFile) { $lastIp = (Get-Content $cacheFile -Raw).Trim() $ageHours = ((Get-Date) - (Get-Item $cacheFile).LastWriteTime).TotalHours if ($ageHours -ge 24) { $forceKeepAlive = $true } } if (($pubIp -eq $lastIp) -and (-not $forceKeepAlive)) { exit 0 } try { $resultText = '' if ($cfg.Provider -eq 'DUCKDNS') { $dom = $cfg.Hostname -replace '\.duckdns\.org$', '' $url = "https://www.duckdns.org/update?domains=$dom&token=$($cfg.Secret)&ip=$pubIp" $resultText = Invoke-RestMethod -Uri $url -TimeoutSec 15 } else { $base = if ($cfg.Provider -eq 'NOIP') { 'https://dynupdate.no-ip.com/nic/update' } else { 'https://members.dyndns.org/nic/update' } $url = "${base}?hostname=$($cfg.Hostname)&myip=$pubIp" $pair = "$($cfg.Username):$($cfg.Secret)" $b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair)) $headers = @{ Authorization = "Basic $b64"; 'User-Agent' = 'PSC-DynDNS-Watchdog/1.0' } $resultText = Invoke-RestMethod -Uri $url -Headers $headers -TimeoutSec 15 } $pubIp | Set-Content -Path $cacheFile -Encoding ASCII Write-DLog "ATUALIZADO ($($cfg.Provider)): Host [$($cfg.Hostname)] -> IP [$pubIp] | Resposta: $resultText" } catch { Write-DLog "ERRO ao atualizar $($cfg.Hostname): $($_.Exception.Message)" } '@ $scriptPath = Join-Path $Global:PSCWatchdogDir 'watchdog_dyndns.ps1' $dynWatchScript | Set-Content -Path $scriptPath -Encoding ASCII $taskName = 'PSC_Watchdog_DynDNS' Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$scriptPath`"" $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes 10) -RepetitionDuration (New-TimeSpan -Days 3650) $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 2) $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'PSC Watchdog: Mantem DynDNS sempre ativo e atualizado a cada 10 min' -Force | Out-Null & $scriptPath Write-Host "`n [OK] Watchdog DynDNS ativo! Tarefa '$taskName' configurada." -ForegroundColor Green if (Test-Path 'C:\PSC-WATCHDOG\dyndns_watchdog.log') { Get-Content 'C:\PSC-WATCHDOG\dyndns_watchdog.log' -Tail 5 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray } } Read-Host "`n Prima Enter para voltar" } # ============================================================================ # MODULO 4: WATCHDOG DE SERVICOS CRITICOS (SQL SERVER / PHC / SAGE / REMOTO) # ============================================================================ function Install-PSCErpServicesWatchdog { Write-PSCServerHeader Write-Host "`n [4] WATCHDOG DE SERVICOS CRITICOS (SQL SERVER / PHC / SAGE / IIS / REMOTO)" -ForegroundColor Yellow Write-Host " Deteta bases de dados e servicos de faturacao e garante que reiniciam sozinhos se cairem." -ForegroundColor Gray $erpSvcs = @(Get-Service | Where-Object { $_.Name -match 'MSSQL|SQLAgent|SQLBrowser|W3SVC|TeamViewer|AnyDesk|TermService|PHC|Sage|Primavera' }) if ($erpSvcs.Count -gt 0) { Write-Host "`n Servicos criticos detetados neste servidor:" -ForegroundColor Cyan foreach ($es in $erpSvcs) { $col = if ($es.Status -eq 'Running') { 'Green' } else { 'Yellow' } Write-Host (" - {0,-28} [{1}] ({2})" -f $es.Name, $es.Status, $es.DisplayName) -ForegroundColor $col } } $defErp = if ($erpSvcs.Count -gt 0) { ($erpSvcs | Where-Object { $_.Status -eq 'Running' } | Select-Object -ExpandProperty Name) -join ',' } else { 'TermService' } $inp = (Read-Host "`n Servicos a blindar separados por virgula (Enter para '$defErp')").Trim() if ([string]::IsNullOrWhiteSpace($inp)) { $inp = $defErp } $targets = @($inp -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) foreach ($sn in $targets) { $s = Get-Service -Name $sn -ErrorAction SilentlyContinue if ($s) { try { Set-Service -Name $sn -StartupType Automatic -ErrorAction SilentlyContinue } catch {} $null = sc.exe failure "$sn" reset= 86400 actions= restart/5000/restart/10000/restart/30000 2>&1 $null = sc.exe failureflag "$sn" 1 2>&1 if ($s.Status -ne 'Running') { Start-Service -Name $sn -ErrorAction SilentlyContinue } Write-Host " [OK] Recuperacao automatica (5s/10s/30s) ativa em: $sn" -ForegroundColor Green } } $arrLit = ($targets | ForEach-Object { "'$_'" }) -join ', ' $erpScript = @" `$ErrorActionPreference = 'SilentlyContinue' `$logFile = 'C:\PSC-WATCHDOG\erp_watchdog.log' `$services = @($arrLit) foreach (`$sName in `$services) { `$s = Get-Service -Name `$sName if (`$s -and `$s.Status -ne 'Running') { `$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' Add-Content -Path `$logFile -Value "[`$ts] ALERTA: Servico [`$sName] parado. A iniciar..." -Encoding UTF8 Start-Service -Name `$sName } } "@ $scriptPath = Join-Path $Global:PSCWatchdogDir 'watchdog_erp.ps1' $erpScript | Set-Content -Path $scriptPath -Encoding ASCII $taskName = 'PSC_Watchdog_Servicos' Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$scriptPath`"" $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650) $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'PSC Watchdog: Servicos SQL/ERP/Remoto sempre ativos (a cada 5 min)' -Force | Out-Null Write-Host "`n [OK] Tarefa '$taskName' ativa (SYSTEM a cada 5 min)!" -ForegroundColor Green Read-Host " Prima Enter para voltar" } # ============================================================================ # MODULO 5: DIAGNOSTICO RAPIDO DE SAUDE DO SERVIDOR & RAIO-X # ============================================================================ function Invoke-PSCServerDiagnostics { Write-PSCServerHeader Write-Host "`n [5] DIAGNOSTICO DE SAUDE DO SERVIDOR & RAIO-X" -ForegroundColor Yellow Write-Host " ----------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " 1. Volumes e Ocupacao de Disco:" -ForegroundColor Cyan $vols = @() Get-Volume -ErrorAction SilentlyContinue | Where-Object { $_.DriveLetter } | ForEach-Object { $totGb = if ($_.Size -gt 0) { [Math]::Round($_.Size / 1GB, 1) } else { 0 } $freGb = [Math]::Round($_.SizeRemaining / 1GB, 1) $pct = if ($_.Size -gt 0) { [Math]::Round((($_.Size - $_.SizeRemaining) / $_.Size) * 100, 1) } else { 0 } $col = if ($pct -ge 90) { 'Red' } elseif ($pct -ge 80) { 'Yellow' } else { 'Green' } Write-Host (" Drive {0}: [{1}] -> {2}% ocupado ({3} GB livres de {4} GB) | Saude: {5}" -f $_.DriveLetter, $_.FileSystemLabel, $pct, $freGb, $totGb, $_.HealthStatus) -ForegroundColor $col $vols += [ordered]@{ Drive = $_.DriveLetter; Label = $_.FileSystemLabel; UsedPct = $pct; FreeGB = $freGb; TotalGB = $totGb; Health = [string]$_.HealthStatus } } Write-Host "`n 2. Discos Fisicos (SMART / RAID):" -ForegroundColor Cyan $disks = @() Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object { $szGb = [Math]::Round($_.Size / 1GB, 0) $col = if ($_.HealthStatus -eq 'Healthy') { 'Green' } else { 'Red' } Write-Host (" - {0} ({1} GB | {2}) -> Saude: {3} | Estado: {4}" -f $_.FriendlyName, $szGb, $_.MediaType, $_.HealthStatus, $_.OperationalStatus) -ForegroundColor $col $disks += [ordered]@{ Model = $_.FriendlyName; SizeGB = $szGb; Media = [string]$_.MediaType; Health = [string]$_.HealthStatus } } Write-Host "`n 3. Portas Criticas de Servidor em Escuta:" -ForegroundColor Cyan $critPorts = @(443, 3389, 445, 1433, 1723, 80, 8080) $openList = @() foreach ($cp in $critPorts) { $listening = Get-NetTCPConnection -LocalPort $cp -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1 if ($listening) { Write-Host (" [ABERTA] Porta {0,-5} (PID: {1})" -f $cp, $listening.OwningProcess) -ForegroundColor Green $openList += $cp } } $sendRx = Read-Host "`n Deseja enviar este Raio-X do Servidor para o Portal PSC? (S/N)" if ($sendRx -match '^[sS]') { $rxObj = [ordered]@{ Tipo = 'RaioX-Servidor' Servidor = $env:COMPUTERNAME DataHora = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') Volumes = $vols DiscosFisicos = $disks PortasAbertas = $openList } $rxJson = $rxObj | ConvertTo-Json -Depth 5 $cleanHost = ($env:COMPUTERNAME -replace '[^A-Za-z0-9_-]', '_') try { $resp = Invoke-RestMethod -Uri $Global:PSCPortalUrl -Method Post -Body @{ token = $Global:PSCPortalToken host = $env:COMPUTERNAME filename = "RaioX-Servidor_${cleanHost}.json" content = $rxJson } -TimeoutSec 15 Write-Host " [OK] Raio-X enviado para: $($resp.url)" -ForegroundColor Green } catch { Write-Host " [ERRO] Falha ao enviar Raio-X: $_" -ForegroundColor Red } } Read-Host "`n Prima Enter para voltar" } # Importar configuracao padrao se estivermos no PC-CASA if ($env:COMPUTERNAME -eq 'PC-CASA') { $autoCfg = [PSCustomObject]@{ Cliente = 'PSC-CASA (Joao Ferrao)' Maquina = 'PC-CASA' TipoDestino = 'SMB' DestinoBase = '\\MyCloud-PKK1ET\ferrao\DIARIO' NasHost = 'MyCloud-PKK1ET' NasIpFallback = '192.168.1.69' NasSharePath = 'ferrao\DIARIO' NasUser = 'ferrao' NasPass = 'Jocafe2009' Origens = @( 'C:\PSC-ANTIGRAVITY', 'C:\Users\Ferrao\OUTLOOK', 'C:\Users\Ferrao\Desktop', 'C:\Users\Ferrao\Documents', 'C:\Users\Ferrao\Downloads', 'C:\Users\Ferrao\Pictures', 'C:\Users\Ferrao\.ssh' ) FecharOutlook = $true Modo = 'INCREMENTAL_SEM_APAGAR' Periodicidade = 'DIARIO' Horario = '12:00' AtivarRotacao6Meses = $true DataInicioCiclo = '2026-11-16' DataProximaFormatacao6M = '2027-05-16' EmailRelatorio = 'backups@proservicecomputer.pt' EnviarEmailRelatorio = $true CriadoEm = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') } if (-not (Test-Path $Global:PSCConfigFile)) { Save-PSCBackupConfig $autoCfg Build-PSCRunnerScript } } # ============================================================================ # LOOP PRINCIPAL DO PSC SERVER TOOLKIT # ============================================================================ while ($true) { Write-PSCServerHeader Write-Host "" Write-Host " [1] Backups de Servidor (Substituto Cobian - 00h01 / Incremental Sem Apagar / Email)" -ForegroundColor Green Write-Host " [2] Central VPN Servidor (Configurar RRAS SSTP + Watchdog VPN Sempre Ativa 5 min)" -ForegroundColor White Write-Host " [3] Watchdog DynDNS Sempre Ativo (Servico Local + Atualizador HTTP Nativo 10 min)" -ForegroundColor White Write-Host " [4] Watchdog de Servicos Criticos (SQL Server, PHC, Sage, IIS, TeamViewer/AnyDesk)" -ForegroundColor White Write-Host " [5] Diagnostico de Saude do Servidor (Discos, RAID, Portas) & Enviar Raio-X" -ForegroundColor White Write-Host " [6] Abrir Dashboard Central de Servidores & Backups no Google Chrome" -ForegroundColor Cyan Write-Host " [0] Sair" -ForegroundColor DarkGray Write-Host "" $choice = Read-Host " Escolha uma opcao" switch ($choice) { '1' { Show-PSCBackupSubMenu } '2' { Show-PSCVpnServerSubMenu } '3' { Install-PSCDynDnsWatchdogServer } '4' { Install-PSCErpServicesWatchdog } '5' { Invoke-PSCServerDiagnostics } '6' { Start-Process 'chrome.exe' 'https://portal.proservicecomputer.pt/servidores/upload_log.php' } '0' { break } } }