Skip to content

Instantly share code, notes, and snippets.

@erinmel
Last active September 4, 2025 01:20
Show Gist options
  • Save erinmel/41395ddc05ff110bcfda474db8f6cfad to your computer and use it in GitHub Desktop.
Save erinmel/41395ddc05ff110bcfda474db8f6cfad to your computer and use it in GitHub Desktop.
PowerShell Config
# Ejecutar como administrador
$logPath = Join-Path -Path $PSScriptRoot -ChildPath "instalador.log"
function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = "[$timestamp] [$Level] $Message"
Add-Content -Path $logPath -Value $line
switch ($Level) {
"ERROR" { Write-Host $line -ForegroundColor Red }
"SUCCESS" { Write-Host $line -ForegroundColor Green }
"WARN" { Write-Host $line -ForegroundColor Yellow }
default { Write-Host $line -ForegroundColor White }
}
}
Write-Log "=== INSTALADOR INTERACTIVO DE ENTORNO DE DESARROLLO ===" "INFO"
# Verificar winget
if (!(Get-Command winget -ErrorAction SilentlyContinue)) {
Write-Log "Winget no esta disponible. Instala App Installer desde Microsoft Store." "ERROR"
exit 1
}
# Funcion para mostrar menu de seleccion multiple
function Show-MultiSelectMenu {
param(
[Parameter(Mandatory = $true)] [string]$Title,
[Parameter(Mandatory = $true)] [array]$Options,
[array]$DefaultSelected = @()
)
$selected = @{}
for ($i = 0; $i -lt $Options.Count; $i++) {
$selected[$i] = $DefaultSelected -contains $i
}
$currentIndex = 0
do {
Clear-Host
Write-Host $Title -ForegroundColor Cyan
Write-Host "Usa arriba/abajo para navegar, ESPACIO para seleccionar, ENTER para continuar" -ForegroundColor Yellow
Write-Host ""
for ($i = 0; $i -lt $Options.Count; $i++) {
$prefix = " "
$checkbox = "[ ]"
$color = "Gray"
if ($i -eq $currentIndex) {
$prefix = ">> "
$color = "White"
}
if ($selected.ContainsKey($i) -and $selected[$i]) {
$checkbox = "[X]"
}
$optionText = $Options[$i]
Write-Host "$prefix$checkbox $optionText" -ForegroundColor $color
}
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
switch ($key.VirtualKeyCode) {
38 { $currentIndex = [Math]::Max(0, $currentIndex - 1) }
40 { $currentIndex = [Math]::Min($Options.Count - 1, $currentIndex + 1) }
32 { $selected[$currentIndex] = -not $selected[$currentIndex] }
}
} while ($key.VirtualKeyCode -ne 13)
$selectedItems = @()
for ($i = 0; $i -lt $Options.Count; $i++) {
if ($selected.ContainsKey($i) -and $selected[$i]) {
$selectedItems += $i
}
}
return $selectedItems
}
# Funcion para mostrar menu de seleccion unica
function Show-SingleSelectMenu {
param(
[Parameter(Mandatory = $true)] [string]$Title,
[Parameter(Mandatory = $true)] [array]$Options,
[int]$DefaultSelected = 0
)
$currentIndex = $DefaultSelected
do {
Clear-Host
Write-Host $Title -ForegroundColor Cyan
Write-Host "Usa arriba/abajo para navegar, ENTER para seleccionar" -ForegroundColor Yellow
Write-Host ""
for ($i = 0; $i -lt $Options.Count; $i++) {
$prefix = " "
$color = "Gray"
if ($i -eq $currentIndex) {
$prefix = ">> "
$color = "White"
}
$optionText = $Options[$i]
Write-Host "$prefix$optionText" -ForegroundColor $color
}
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
switch ($key.VirtualKeyCode) {
38 { $currentIndex = [Math]::Max(0, $currentIndex - 1) }
40 { $currentIndex = [Math]::Min($Options.Count - 1, $currentIndex + 1) }
}
} while ($key.VirtualKeyCode -ne 13)
return $currentIndex
}
# Funcion para pedir entrada con valor por defecto
function Get-InputWithDefault {
param([string]$Prompt, [string]$Default = "")
if ($Default) {
$userInput = Read-Host "$Prompt [$Default]"
if ($userInput) {
return $userInput
} else {
return $Default
}
} else {
return Read-Host $Prompt
}
}
# Funcion para obtener versiones disponibles de Java via winget (FIXED)
function Get-JavaVersions {
param([string]$SearchId)
try {
Write-Host "Buscando versiones disponibles de $SearchId..." -ForegroundColor Yellow
# Usar --id con el prefijo exacto y capturar tanto stdout como stderr
$wingetOutput = & winget search --id=$SearchId --accept-source-agreements 2>&1 | Out-String
$versions = @()
$lines = $wingetOutput -split "`r?`n"
# Buscar lineas que contengan el ID y extraer el package ID completo
foreach ($line in $lines) {
# Saltar headers y lineas vacias
if ($line -match "^-+$" -or $line -match "Name.*Id.*Version" -or [string]::IsNullOrWhiteSpace($line)) {
continue
}
# Buscar lineas que contengan nuestro SearchId
if ($line -match $SearchId) {
# Dividir la linea por espacios y buscar el ID (segunda columna)
$parts = $line -split '\s+' | Where-Object { $_ -ne '' }
if ($parts.Length -ge 2) {
$packageId = $parts[1]
# Verificar que sea un ID valido y que contenga nuestro prefijo
if ($packageId -match "^$SearchId" -and $packageId -ne "Id") {
$versions += $packageId
}
}
}
}
# Remover duplicados y ordenar
$uniqueVersions = $versions | Sort-Object | Get-Unique
Write-Host "Encontradas $($uniqueVersions.Count) versiones" -ForegroundColor Green
return $uniqueVersions
} catch {
Write-Log "ERROR - No se pudieron obtener versiones de $SearchId`: $($_.Exception.Message)" "ERROR"
return @()
}
}
# === SELECCION DE JAVA JDK ===
$javaDistributions = @(
"Amazon Corretto",
"Eclipse Temurin",
"Microsoft OpenJDK",
"Oracle JDK",
"Azul Zulu",
"Ninguno"
)
$javaSearchIds = @{
"Amazon Corretto" = "Amazon.Corretto"
"Eclipse Temurin" = "EclipseAdoptium.Temurin"
"Microsoft OpenJDK" = "Microsoft.OpenJDK"
"Oracle JDK" = "Oracle.JDK"
"Azul Zulu" = "Azul.Zulu"
}
# Versiones fallback en caso de que winget search falle
$javaFallbackVersions = @{
"Amazon Corretto" = @("Amazon.Corretto.8.JDK", "Amazon.Corretto.11.JDK", "Amazon.Corretto.17.JDK", "Amazon.Corretto.21.JDK", "Amazon.Corretto.22.JDK", "Amazon.Corretto.23.JDK", "Amazon.Corretto.24.JDK")
"Eclipse Temurin" = @("EclipseAdoptium.Temurin.8.JDK", "EclipseAdoptium.Temurin.11.JDK", "EclipseAdoptium.Temurin.17.JDK", "EclipseAdoptium.Temurin.21.JDK", "EclipseAdoptium.Temurin.22.JDK", "EclipseAdoptium.Temurin.23.JDK", "EclipseAdoptium.Temurin.24.JDK")
"Microsoft OpenJDK" = @("Microsoft.OpenJDK.11", "Microsoft.OpenJDK.16", "Microsoft.OpenJDK.17", "Microsoft.OpenJDK.21")
"Oracle JDK" = @("Oracle.JDK.17", "Oracle.JDK.18", "Oracle.JDK.19", "Oracle.JDK.20", "Oracle.JDK.21", "Oracle.JDK.22", "Oracle.JDK.23", "Oracle.JDK.24")
"Azul Zulu" = @("Azul.Zulu.8.JDK", "Azul.Zulu.11.JDK", "Azul.Zulu.17.JDK", "Azul.Zulu.21.JDK", "Azul.Zulu.22.JDK", "Azul.Zulu.23.JDK", "Azul.Zulu.24.JDK")
}
$selectedJavaDistribution = Show-SingleSelectMenu -Title "Selecciona una distribucion de Java JDK:" -Options $javaDistributions -DefaultSelected 0
$selectedJavaPackage = ""
if ($selectedJavaDistribution -lt ($javaDistributions.Count - 1)) {
$selectedDistribution = $javaDistributions[$selectedJavaDistribution]
$searchId = $javaSearchIds[$selectedDistribution]
# Obtener versiones disponibles
$availableVersions = Get-JavaVersions -SearchId $searchId
# Si no encontramos versiones via winget, usar fallback
if ($availableVersions.Count -eq 0) {
Write-Host "No se pudieron obtener versiones via winget search. Usando versiones conocidas..." -ForegroundColor Yellow
$availableVersions = $javaFallbackVersions[$selectedDistribution]
}
if ($availableVersions.Count -gt 0) {
# Filtrar solo JDK (no JRE) y ordenar
$jdkVersions = $availableVersions | Where-Object { $_ -match "JDK|\.1[0-9]$|\.2[0-9]$|\.8$" -and $_ -notmatch "JRE" } | Sort-Object
if ($jdkVersions.Count -eq 0) {
# Si no hay JDK específicos, usar todas las versiones disponibles
$jdkVersions = $availableVersions | Sort-Object
}
if ($jdkVersions.Count -gt 0) {
$displayVersions = @()
foreach ($version in $jdkVersions) {
# Extraer numero de version para mejor display
if ($version -match "\.(\d+)\.JDK") {
$javaVersion = $matches[1]
$displayName = "$selectedDistribution JDK $javaVersion ($version)"
} elseif ($version -match "\.(\d+)$") {
$javaVersion = $matches[1]
$displayName = "$selectedDistribution JDK $javaVersion ($version)"
} else {
$displayName = "$selectedDistribution ($version)"
}
$displayVersions += $displayName
}
$versionTitle = "Selecciona la version de " + $selectedDistribution + ":"
$selectedVersion = Show-SingleSelectMenu -Title $versionTitle -Options $displayVersions -DefaultSelected 0
$selectedJavaPackage = $jdkVersions[$selectedVersion]
Write-Log "Java seleccionado: $selectedJavaPackage" "INFO"
} else {
Write-Host "No se encontraron versiones JDK disponibles para $selectedDistribution" -ForegroundColor Red
Read-Host "Presiona ENTER para continuar sin Java"
}
} else {
Write-Host "No se pudieron obtener versiones de $selectedDistribution" -ForegroundColor Red
Read-Host "Presiona ENTER para continuar sin Java"
}
}
# === SELECCION DE APLICACIONES ===
$devTools = @("Node.js LTS","Python 3.12","Git","Delta (Git diff tool)","GitHub CLI","Docker Desktop")
$devApps = @("OpenJS.NodeJS.LTS","Python.Python.3.12","Git.Git","dandavison.delta","GitHub.cli","Docker.DockerDesktop")
$selectedDev = Show-MultiSelectMenu -Title "Selecciona las herramientas de desarrollo:" -Options $devTools -DefaultSelected @(0,1,2,3,4)
$editors = @("Visual Studio Code","JetBrains Toolbox","Sublime Text","Notepad++")
$editorApps = @("Microsoft.VisualStudioCode","JetBrains.Toolbox","SublimeHQ.SublimeText.4","Notepad++.Notepad++")
$selectedEditors = Show-MultiSelectMenu -Title "Selecciona editores/IDEs:" -Options $editors -DefaultSelected @(0)
$terminalTools = @("Windows Terminal","PowerShell 7","Oh My Posh","JetBrains Mono Nerd Font","Starship Prompt")
$terminalApps = @("Microsoft.WindowsTerminal","Microsoft.PowerShell","JanDeDobbeleer.OhMyPosh","DEVCOM.JetBrainsMonoNerdFont","Starship.Starship")
$selectedTerminal = Show-MultiSelectMenu -Title "Selecciona herramientas de terminal:" -Options $terminalTools -DefaultSelected @(0,1,2,3)
$browsers = @("Google Chrome","Mozilla Firefox","Microsoft Edge Dev","Brave Browser")
$browserApps = @("Google.Chrome","Mozilla.Firefox","Microsoft.EdgeDev","Brave.Brave")
$selectedBrowsers = Show-MultiSelectMenu -Title "Selecciona navegadores:" -Options $browsers
$extraApps = @("Postman","Insomnia (REST Client)","VLC Media Player","Discord","Steam","7-Zip","WinRAR")
$extraAppIds = @("Postman.Postman","Kong.Insomnia","VideoLAN.VLC","Discord.Discord","Valve.Steam","7zip.7zip","RARLab.WinRAR")
$selectedExtra = Show-MultiSelectMenu -Title "Selecciona aplicaciones adicionales:" -Options $extraApps
# === CONFIGURACION DE GIT ===
$gitConfigs = @(
"Configurar default branch como main",
"Configurar nombre de usuario",
"Configurar email",
"Generar clave SSH para GitHub",
"Configurar GitHub CLI (requiere token)"
)
$selectedGitConfigs = Show-MultiSelectMenu -Title "Configuracion de Git (requiere tener Git seleccionado):" -Options $gitConfigs -DefaultSelected @(0,1,2)
# === INSTALACION ===
$allSelectedApps = @()
# Agregar Java si se selecciono
if ($selectedJavaPackage) {
$allSelectedApps += $selectedJavaPackage
}
# Agregar otras aplicaciones
foreach ($i in $selectedDev) { $allSelectedApps += $devApps[$i] }
foreach ($i in $selectedEditors) { $allSelectedApps += $editorApps[$i] }
foreach ($i in $selectedTerminal){ $allSelectedApps += $terminalApps[$i] }
foreach ($i in $selectedBrowsers){ $allSelectedApps += $browserApps[$i] }
foreach ($i in $selectedExtra) { $allSelectedApps += $extraAppIds[$i] }
$appsString = $allSelectedApps -join ", "
Write-Log "Aplicaciones a instalar: $appsString" "INFO"
$confirm = Read-Host "Continuar con la instalacion? (s/n)"
if ($confirm -notin @("s","S")) {
Write-Log "Instalacion cancelada por el usuario" "WARN"
exit
}
# Instalar aplicaciones
foreach ($app in $allSelectedApps) {
Write-Log "Instalando $app..." "INFO"
try {
# Usar --id y -e para paquetes que lo requieren
if ($app -like "Amazon.Corretto*" -or $app -like "EclipseAdoptium*" -or $app -like "Microsoft.OpenJDK*" -or $app -like "Oracle.JDK*" -or $app -like "Azul.Zulu*") {
$result = winget install --id=$app -e --accept-package-agreements --accept-source-agreements -h 2>&1
} else {
$result = winget install $app --accept-package-agreements --accept-source-agreements -h 2>&1
}
Write-Log "OK - $app instalado correctamente" "SUCCESS"
} catch {
$errorMessage = $_.Exception.Message
Write-Log "ERROR - Fallo instalando $app - $errorMessage" "ERROR"
}
}
# === CONFIGURACION DE GIT ===
if (2 -in $selectedDev -and $selectedGitConfigs.Count -gt 0) {
Write-Log "Configurando Git..." "INFO"
# Configurar default branch como main
if (0 -in $selectedGitConfigs) {
try {
$gitResult = git config --global init.defaultBranch main 2>&1
Write-Log "OK - Default branch configurado como main" "SUCCESS"
} catch {
Write-Log "ERROR - No se pudo configurar default branch" "ERROR"
}
}
# Configurar nombre de usuario
if (1 -in $selectedGitConfigs) {
$gitName = Read-Host "Ingresa tu nombre para Git"
if ($gitName) {
try {
$gitResult = git config --global user.name "$gitName" 2>&1
Write-Log "OK - Nombre de usuario configurado: $gitName" "SUCCESS"
} catch {
Write-Log "ERROR - No se pudo configurar el nombre de usuario" "ERROR"
}
}
}
# Configurar email
if (2 -in $selectedGitConfigs) {
$gitEmail = Read-Host "Ingresa tu email para Git"
if ($gitEmail) {
try {
$gitResult = git config --global user.email "$gitEmail" 2>&1
Write-Log "OK - Email configurado: $gitEmail" "SUCCESS"
} catch {
Write-Log "ERROR - No se pudo configurar el email" "ERROR"
}
}
}
# Generar clave SSH
if (3 -in $selectedGitConfigs) {
$sshKeyName = Get-InputWithDefault -Prompt "Nombre para la clave SSH" -Default "github"
$sshPath = "$env:USERPROFILE\.ssh\$sshKeyName"
if (!(Test-Path "$env:USERPROFILE\.ssh")) {
New-Item -ItemType Directory -Path "$env:USERPROFILE\.ssh" -Force | Out-Null
}
try {
$sshResult = ssh-keygen -t ed25519 -C "$gitEmail" -f "$sshPath" -N '""' 2>&1
# Configurar SSH config
$sshConfig = "$env:USERPROFILE\.ssh\config"
$configContent = "`n# GitHub`nHost github.com`n HostName github.com`n User git`n IdentityFile ~/.ssh/$sshKeyName`n"
Add-Content -Path $sshConfig -Value $configContent
# Agregar clave al ssh-agent
Start-Service ssh-agent -ErrorAction SilentlyContinue
ssh-add "$sshPath"
Write-Log "OK - Clave SSH generada: $sshPath" "SUCCESS"
Write-Host "`nClave SSH publica (copia esto en GitHub):" -ForegroundColor Yellow
Get-Content "$sshPath.pub"
Write-Host "`nVe a https://github.com/settings/keys para agregar esta clave" -ForegroundColor Cyan
Read-Host "Presiona ENTER cuando hayas agregado la clave en GitHub"
} catch {
$sshError = $_.Exception.Message
Write-Log "ERROR - No se pudo generar la clave SSH: $sshError" "ERROR"
}
}
# Configurar GitHub CLI
if (4 -in $selectedGitConfigs) {
Write-Host "`nPara configurar GitHub CLI necesitas un Personal Access Token:" -ForegroundColor Yellow
Write-Host "1. Ve a https://github.com/settings/tokens" -ForegroundColor Cyan
Write-Host "2. Click en Generate new token classic" -ForegroundColor Cyan
Write-Host "3. Selecciona estos permisos minimos:" -ForegroundColor Cyan
Write-Host " - repo (acceso completo a repositorios)" -ForegroundColor White
Write-Host " - workflow (para GitHub Actions)" -ForegroundColor White
Write-Host " - user:email (acceso al email)" -ForegroundColor White
Write-Host " - read:org (si trabajas con organizaciones)" -ForegroundColor White
Write-Host "`nNOTA: No necesitas permisos de administrador" -ForegroundColor Green
$setupGH = Read-Host "`nQuieres configurar GitHub CLI ahora? (s/n)"
if ($setupGH -in @("s","S")) {
try {
gh auth login
Write-Log "OK - GitHub CLI configurado" "SUCCESS"
} catch {
$ghError = $_.Exception.Message
Write-Log "ERROR - No se pudo configurar GitHub CLI: $ghError" "ERROR"
Write-Host "Puedes configurarlo manualmente despues con: gh auth login" -ForegroundColor Yellow
}
}
}
}
# === CONFIGURACION ADICIONAL DE JAVA ===
if ($selectedJavaPackage) {
Write-Host "`n=== CONFIGURACION DE JAVA ===" -ForegroundColor Cyan
Write-Host "Java se ha instalado correctamente." -ForegroundColor Green
Write-Host "Puede que necesites reiniciar tu terminal para que las variables de entorno se actualicen." -ForegroundColor Yellow
# Intentar mostrar version de Java instalada
try {
$javaVersionOutput = java -version 2>&1
$javaVersionLine = $javaVersionOutput | Select-String "version" | Select-Object -First 1
if ($javaVersionLine) {
Write-Host "Version de Java detectada: $javaVersionLine" -ForegroundColor Green
}
} catch {
Write-Host "Reinicia tu terminal y ejecuta java -version para verificar la instalacion" -ForegroundColor Yellow
}
}
# === FINAL ===
Write-Log "=== INSTALACION COMPLETADA ===" "SUCCESS"
Write-Log "Log guardado en: $logPath" "INFO"
Write-Host "`n=== RESUMEN ===" -ForegroundColor Green
if ($selectedJavaPackage) {
Write-Host "Java: $selectedJavaPackage" -ForegroundColor White
}
$appCount = $allSelectedApps.Count
Write-Host "Aplicaciones instaladas: $appCount" -ForegroundColor White
Write-Host "Log completo en: $logPath" -ForegroundColor White
if (3 -in $selectedGitConfigs) {
Write-Host "`nRecuerda:" -ForegroundColor Yellow
Write-Host "- Probar la conexion SSH: ssh -T [email protected]" -ForegroundColor Cyan
Write-Host "- La clave SSH ya esta configurada en ~/.ssh/config" -ForegroundColor Cyan
}
Write-Host "`nInstalacion finalizada. Disfruta tu nuevo entorno de desarrollo!" -ForegroundColor Green
Write-Host "Tip: Reinicia tu terminal para asegurar que todas las variables de entorno esten actualizadas." -ForegroundColor Yellow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment