This commit is contained in:
2026-09-24 14:47:12 +00:00
parent af55c8d5e7
commit 8ae55b0750
2 changed files with 1222 additions and 1019 deletions

View File

@@ -14,6 +14,8 @@ echo ============================================================
echo El instalador ha terminado.
echo ============================================================
echo.
echo Codigo de salida: %errorlevel%
echo.
if errorlevel 1 (
echo ERROR: el instalador ha terminado con errores.

257
setup.ps1
View File

@@ -19,6 +19,7 @@
- Añade "tecnica" al grupo Usuarios de escritorio remoto.
- Oculta "tecnica" de la lista de usuarios del login.
- Verifica el estado real al finalizar.
- Registra todos los pasos y errores en %TEMP%\crb-setup.log.
- Devuelve 0 si todo está correcto.
- Devuelve 1 si hay algún error.
@@ -32,6 +33,9 @@
$Username = "tecnica"
# Ruta del log de diagnóstico.
$LogPath = Join-Path $env:TEMP "crb-setup.log"
# ============================================================
# CONFIGURACIÓN DE ERRORES
# ============================================================
@@ -51,6 +55,8 @@ function Write-Step {
Write-Host "==================================================" -ForegroundColor DarkGray
Write-Host $Message -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor DarkGray
Write-Log "[PASO] $Message"
}
function Write-Ok {
@@ -59,6 +65,8 @@ function Write-Ok {
)
Write-Host "[OK] $Message" -ForegroundColor Green
Write-Log "[OK] $Message"
}
function Write-WarningMessage {
@@ -67,6 +75,8 @@ function Write-WarningMessage {
)
Write-Host "[AVISO] $Message" -ForegroundColor Yellow
Write-Log "[AVISO] $Message"
}
function Write-ErrorMessage {
@@ -75,6 +85,58 @@ function Write-ErrorMessage {
)
Write-Host "[ERROR] $Message" -ForegroundColor Red
Write-Log "[ERROR] $Message"
}
# ============================================================
# ESCRIBIR EN LOG
# ============================================================
function Write-Log {
param (
[string]$Message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
try {
Add-Content `
-LiteralPath $LogPath `
-Value "$timestamp $Message" `
-Encoding UTF8 `
-ErrorAction SilentlyContinue
}
catch {
# El log nunca debe interrumpir la ejecución del script.
}
}
# ============================================================
# OBTENER MENSAJE COMPLETO DE UNA EXCEPCIÓN
# ============================================================
function Get-ExceptionMessage {
param (
[Parameter(Mandatory)]
[System.Exception]$Exception
)
$parts = New-Object System.Collections.Generic.List[string]
$current = $Exception
while ($null -ne $current) {
$parts.Add($current.Message)
$current = $current.InnerException
}
return ($parts -join " << ")
}
# ============================================================
@@ -112,9 +174,48 @@ function Ensure-Administrator {
exit 1
}
# --------------------------------------------------------
# ELEVACIÓN DESDE RUTA DE RED (UNC)
# --------------------------------------------------------
# El proceso elevado puede perder el acceso a la carpeta de
# red (\\servidor\...). Para evitarlo, se copia el script
# a %TEMP% y se eleva ejecutando la copia local.
$scriptPath = $PSCommandPath
$tempCopy = $null
if ($scriptPath -like "\\*") {
Write-WarningMessage "El script está en una ruta de red (UNC)."
Write-Host "Copiando a la carpeta temporal para poder elevarse..." `
-ForegroundColor Yellow
$tempCopy = Join-Path $env:TEMP (
"crb-setup-" + [guid]::NewGuid().ToString("N") + ".ps1"
)
try {
$quotedScript = '"' + $PSCommandPath + '"'
Copy-Item `
-LiteralPath $PSCommandPath `
-Destination $tempCopy `
-Force `
-ErrorAction Stop
}
catch {
Write-ErrorMessage "No se pudo copiar el script a la carpeta temporal."
Write-ErrorMessage $_.Exception.Message
exit 1
}
$scriptPath = $tempCopy
}
$quotedScript = '"' + $scriptPath + '"'
try {
$process = Start-Process `
-FilePath "powershell.exe" `
@@ -129,16 +230,30 @@ function Ensure-Administrator {
-Wait `
-PassThru `
-ErrorAction Stop
exit $process.ExitCode
}
catch {
if ($tempCopy) {
Remove-Item `
-LiteralPath $tempCopy `
-Force `
-ErrorAction SilentlyContinue
}
Write-ErrorMessage "No se pudo obtener permisos de Administrador."
Write-ErrorMessage $_.Exception.Message
exit 1
}
if ($tempCopy) {
Remove-Item `
-LiteralPath $tempCopy `
-Force `
-ErrorAction SilentlyContinue
}
exit $process.ExitCode
}
# ============================================================
@@ -406,6 +521,25 @@ function Ensure-TechnicalUser {
}
}
# ============================================================
# OBTENER REGLAS DE FIREWALL DE ESCRITORIO REMOTO
# ============================================================
function Get-RdpFirewallRules {
$rdpGroupNames = @("Remote Desktop", "Escritorio remoto")
$rules = @(
Get-NetFirewallRule `
-ErrorAction Stop |
Where-Object {
$rdpGroupNames -contains $_.DisplayGroup
}
)
return $rules
}
# ============================================================
# ACTIVAR ESCRITORIO REMOTO
# ============================================================
@@ -486,39 +620,80 @@ function Enable-RemoteDesktop {
Write-Ok "Servicio TermService funcionando."
# --------------------------------------------------------
# SERVICIO DE FIREWALL
# --------------------------------------------------------
$firewallService = Get-Service `
-Name "mpssvc" `
-ErrorAction Stop
if ($firewallService.Status -ne "Running") {
Write-Host "El servicio de Firewall no está activo. Iniciándolo..." `
-ForegroundColor Yellow
if ($firewallService.StartType -eq "Disabled") {
Set-Service `
-Name "mpssvc" `
-StartupType Automatic `
-ErrorAction Stop
}
Start-Service `
-Name "mpssvc" `
-ErrorAction Stop
$firewallService = Get-Service `
-Name "mpssvc" `
-ErrorAction Stop
if ($firewallService.Status -ne "Running") {
throw "No se pudo iniciar el servicio de Firewall (mpssvc)."
}
}
Write-Ok "Servicio de Firewall de Windows activo."
# --------------------------------------------------------
# FIREWALL
# --------------------------------------------------------
$firewallRules = Get-NetFirewallRule `
-ErrorAction Stop |
Where-Object {
$_.DisplayGroup -eq "Remote Desktop" -or
$_.DisplayGroup -eq "Escritorio remoto"
$rules = Get-RdpFirewallRules
if ($rules.Count -eq 0) {
Write-Host "No se hallaron reglas RDP por grupo. Probando con netsh..." `
-ForegroundColor Yellow
& netsh.exe advfirewall firewall set rule group="Remote Desktop" new enable=yes | Out-Null
& netsh.exe advfirewall firewall set rule group="Escritorio remoto" new enable=yes | Out-Null
$rules = Get-RdpFirewallRules
}
if ($null -eq $firewallRules) {
if ($rules.Count -eq 0) {
throw "No se encontraron las reglas de Firewall de Escritorio remoto."
throw "No se encontraron reglas de Firewall de Escritorio remoto (grupo 'Remote Desktop'/'Escritorio remoto')."
}
$firewallRules |
$rules |
Enable-NetFirewallRule `
-ErrorAction Stop
# Verificación REAL de las reglas.
$enabledRules = Get-NetFirewallRule `
-ErrorAction Stop |
$enabledRules = @(
Get-RdpFirewallRules |
Where-Object {
(
$_.DisplayGroup -eq "Remote Desktop" -or
$_.DisplayGroup -eq "Escritorio remoto"
) -and
$_.Enabled -eq "True"
}
)
if ($null -eq $enabledRules) {
if ($enabledRules.Count -eq 0) {
throw "No hay ninguna regla de Firewall de RDP habilitada."
}
@@ -707,30 +882,36 @@ function Test-FinalConfiguration {
try {
$enabledRules = Get-NetFirewallRule `
-ErrorAction Stop |
$enabledRules = @(
Get-RdpFirewallRules |
Where-Object {
(
$_.DisplayGroup -eq "Remote Desktop" -or
$_.DisplayGroup -eq "Escritorio remoto"
) -and
$_.Enabled -eq "True"
}
)
if ($null -ne $enabledRules) {
if ($enabledRules.Count -gt 0) {
Write-Ok "Firewall RDP: HABILITADO"
}
else {
Write-ErrorMessage "Firewall RDP: NO HABILITADO"
$allRdpRules = @(Get-RdpFirewallRules)
if ($allRdpRules.Count -eq 0) {
Write-ErrorMessage "Firewall RDP: NO HAY REGLAS RDP EN EL SISTEMA"
}
else {
Write-ErrorMessage "Firewall RDP: LAS REGLAS EXISTEN PERO ESTÁN DESHABILITADAS"
}
$allOk = $false
}
}
catch {
Write-ErrorMessage "No se pudo comprobar el Firewall de RDP."
Write-ErrorMessage "No se pudo comprobar el Firewall de RDP: $($_.Exception.Message)"
$allOk = $false
}
@@ -830,6 +1011,11 @@ try {
Clear-Host
Write-Log "========== INICIO DE EJECUCIÓN =========="
Write-Log "Windows: $([Environment]::OSVersion.VersionString)"
Write-Log "Usuario: $([Environment]::UserDomainName)\$([Environment]::UserName)"
Write-Log "Elevado (Administrador): $(Test-IsAdministrator)"
Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host " WINDOWS 10 - CONFIGURACIÓN INICIAL" -ForegroundColor Cyan
@@ -977,13 +1163,24 @@ try {
}
catch {
$fullMessage = Get-ExceptionMessage -Exception $_.Exception
Write-Host ""
Write-Host "==================================================" -ForegroundColor Red
Write-Host " ERROR FATAL" -ForegroundColor Red
Write-Host "==================================================" -ForegroundColor Red
Write-Host ""
Write-ErrorMessage $_.Exception.Message
Write-ErrorMessage $fullMessage
Write-Host ""
Write-Host "Trace del script:" -ForegroundColor Yellow
Write-Host $_.ScriptStackTrace
Write-Log "=========================================================================="
Write-Log "ERROR FATAL: $fullMessage"
Write-Log ("TRACE: " + ($_.ScriptStackTrace -replace "(`r)?`n", " | "))
Write-Log "=========================================================================="
Write-Host ""
Write-Host "El script se ha detenido para evitar continuar" `
@@ -991,6 +1188,10 @@ catch {
Write-Host "con una configuración incompleta." `
-ForegroundColor Yellow
Write-Host ""
Write-Host "Detalles guardados en el log: $LogPath" `
-ForegroundColor Cyan
Write-Host ""
exit 1