Skip to content

Instantly share code, notes, and snippets.

@guinetik
Last active October 19, 2025 01:29
Show Gist options
  • Select an option

  • Save guinetik/2666a292131fb67ac80fe44cb57483a5 to your computer and use it in GitHub Desktop.

Select an option

Save guinetik/2666a292131fb67ac80fe44cb57483a5 to your computer and use it in GitHub Desktop.
$global:packages = @(
@{
Name = "Maven"
Description = "Ferramenta de build para Java. Utilizada para compilar e empacotar o projeto."
Url = "https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.zip"
TargetFolder = "apache-maven-3.9.9"
IsOptional = $false
},
@{
Name = "Maven Daemon (mvnd)"
Description = "Um daemon otimizado para o Maven. Utilizado para acelerar o build do projeto."
Url = "https://dlcdn.apache.org/maven/mvnd/1.0.2/maven-mvnd-1.0.2-windows-amd64.zip"
TargetFolder = "maven-mvnd-1.0.2"
IsOptional = $true
},
@{
Name = "Wildfly 16.0.0.Final"
Description = "Servidor de aplicações Java EE."
Url = "https://download.jboss.org/wildfly/16.0.0.Final/wildfly-16.0.0.Final.tar.gz"
TargetFolder = "wildfly-16.0.0.Final"
},
@{
Name = "Eclipse"
Description = "IDE para desenvolvimento Java."
Url = "https://eclipse.c3sl.ufpr.br/technology/epp/downloads/release/2025-03/R/eclipse-jee-2025-03-R-win32-x86_64.zip"
TargetFolder = "eclipse"
IsOptional = $true
}
)
<#
.SYNOPSIS
Instala todos os pacotes.
.DESCRIPTION
Instala todos os pacotes, chamando a função Install-Package para cada um.
.EXAMPLE
PS C:\> Install-Packages
#>
function Install-Packages {
foreach ($package in $packages) {
if ($package.IsOptional) {
# check if the package is already installed
if (Test-Path (Join-Path $toolsDir $package.TargetFolder)) {
Write-Host "✅ $($package.Name) já instalado." -ForegroundColor Green
continue
}
# prompt user
$install = Read-Host "Deseja instalar o pacote opcional $($package.Name)? (S/N)"
if ($install -eq "N" -or $install -eq "n") {
continue
}
}
$folder = Join-Path $toolsDir $package.TargetFolder
$resultado = Install-Package -Nome $package.Name -Url $package.Url -Destino $folder -Description $package.Description
if (-not $resultado) {
$script:instalacaoComSucesso = $false
$script:erroMensagem = "Falha ao instalar $($package.Name)"
throw "Falha ao instalar $($package.Name)"
}
}
}
<#
.SYNOPSIS
Instala um pacote.
.DESCRIPTION
Instala um pacote, baixando-o, extraindo-o e copiando-o para o destino final.
.EXAMPLE
PS C:\> Install-Package -Nome "jdk8u452-b09" -Url "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u452-b09/OpenJDK8U-jdk_x64_windows_hotspot_8u452b09.zip" -Destino "C:\tools"
#>
function Install-Package {
param (
[string]$Nome,
[string]$Url,
[string]$Destino,
[string]$Description
)
Write-Host "----------------------------------------"
Write-Host "📦 Pacote: $Nome"
Write-Host "📝 Descrição: $Description"
if (Test-Path $Destino) {
Write-Host "✅ $Nome já instalado." -ForegroundColor Green
return $true
}
# Cria um diretório temporário para extração do pacote
$extractTempDir = "$tempDir\extract_$(Split-Path -Leaf $Destino)"
New-Item -ItemType Directory -Path $extractTempDir -Force | Out-Null
$arquivoTemp = "$tempDir\$([System.IO.Path]::GetFileName($Url))"
try {
# Passo 1: Download
if (-not (Get-Package -Url $Url -OutputPath $arquivoTemp -packageName $Nome -Description $Description)) {
throw "Falha no download do pacote $Nome"
}
# Passo 2: Extração
if (-not (Unpack -ArchivePath $arquivoTemp -DestinationPath $extractTempDir -packageName $Nome)) {
throw "Falha na extração do pacote $Nome"
}
# Passo 3: Copiar para destino final
if (-not (Copy-Package -SourceDir $extractTempDir -DestinationDir $Destino -packageName $Nome)) {
throw "Falha ao copiar $Nome para o destino final"
}
Write-Host "✅ $Nome instalado com sucesso." -ForegroundColor Green
Write-Host "----------------------------------------"
return $true
}
catch {
Write-Host "❌ Erro ao instalar $Nome : $_" -ForegroundColor Red
Write-Host "----------------------------------------"
return $false
}
finally {
# Limpar arquivos temporários específicos deste pacote
if (Test-Path $arquivoTemp) {
Remove-Item $arquivoTemp -Force -ErrorAction SilentlyContinue
}
if (Test-Path $extractTempDir) {
Remove-Item $extractTempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
}
<#
.SYNOPSIS
Baixa um arquivo da internet.
.DESCRIPTION
Baixa um arquivo da internet, exibindo um indicador de progresso e verificando se o download foi bem-sucedido.
.EXAMPLE
PS C:\> Get-Package -Url "https://example.com/arquivo.zip" -OutputPath "C:\temp\arquivo.zip" -packageName "arquivo"
#>
function Get-Package {
param (
[string]$Url,
[string]$OutputPath,
[string]$packageName,
[string]$Description
)
Write-Host "⬇️ Baixando $packageName..." -ForegroundColor Cyan
$bitsAvailable = $false
try {
# Check if BITS module is available
if (Get-Module -ListAvailable -Name BitsTransfer) {
Import-Module BitsTransfer -ErrorAction Stop
$bitsAvailable = $true
}
} catch {
$bitsAvailable = $false
}
if ($bitsAvailable) {
try {
# Try BITS first
Start-BitsTransfer -Source $Url -Destination $OutputPath -ErrorAction Stop -DisplayName $packageName -Description $Description
Write-Host "✅ Download de $packageName concluído (via BITS)." -ForegroundColor Green
return $true
} catch {
Write-Host "⚠️ BITS falhou, tentando WebClient..." -ForegroundColor Yellow
Write-Host "❌ Erro: $_" -ForegroundColor DarkGray
return $false
}
}
# Fallback to WebClient
try {
Write-Host "⌛ Por Favor, aguarde..." -ForegroundColor Yellow
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile($Url, $OutputPath)
if (Test-Path $OutputPath -and (Get-Item $OutputPath).Length -gt 0) {
Write-Host "✅ Download de $packageName concluído (via WebClient)." -ForegroundColor Green
return $true
} else {
throw "Arquivo baixado está vazio ou não existe."
}
} catch {
Write-Host "❌ Erro: $_" -ForegroundColor DarkGray
return $false
}
return $false
}
<#
.SYNOPSIS
Extrai um arquivo compactado.
.DESCRIPTION
Extrai um arquivo compactado, determinando o tipo de arquivo pela extensão e expandindo ou descompactando conforme o caso.
.EXAMPLE
PS C:\> Unpack -ArchivePath "C:\temp\jdk8u452-b09.zip" -DestinationPath "C:\tools" -packageName "jdk8u452-b09"
#>
function Unpack {
param (
[string]$ArchivePath,
[string]$DestinationPath,
[string]$packageName
)
try {
Write-Host "🗜 Extraindo $packageName..." -ForegroundColor Yellow
# Determinar o tipo de arquivo pela extensão
$extension = [System.IO.Path]::GetExtension($ArchivePath).ToLower()
if ($extension -eq ".zip") {
Expand-Archive -Path $ArchivePath -DestinationPath $DestinationPath -Force
return $true
}
elseif ($ArchivePath -like "*.tar.gz" -or $extension -eq ".gz") {
# Chamar a função para extrair arquivos tar
Expand-TarArchive -ArchivePath $ArchivePath -DestinationPath $DestinationPath
return $true
}
else {
throw "Formato de arquivo não suportado: $extension"
}
# Pequeno delay para garantir que os arquivos sejam liberados
Start-Sleep -Seconds 1
return $true
}
catch {
Write-Host "❌ Erro na extração: $_" -ForegroundColor Red
return $false
}
}
<#
.SYNOPSIS
Extrai um arquivo tar.gz.
.DESCRIPTION
Extrai um arquivo tar.gz usando o comando tar nativo do Windows ou 7-Zip como fallback.
.PARAMETER ArchivePath
Caminho para o arquivo tar.gz a ser extraído.
.PARAMETER DestinationPath
Diretório onde os arquivos serão extraídos.
.EXAMPLE
PS C:\> Extract-TarArchive -ArchivePath "C:\temp\arquivo.tar.gz" -DestinationPath "C:\temp\destino"
#>
function Expand-TarArchive {
param (
[string]$ArchivePath,
[string]$DestinationPath
)
try {
# Verificar se o diretório de destino existe
if (-not (Test-Path $DestinationPath)) {
New-Item -ItemType Directory -Path $DestinationPath -Force | Out-Null
}
# Tentar usar o comando tar nativo do Windows 10+
if (Get-Command tar -ErrorAction SilentlyContinue) {
Write-Host "📦 Extraindo usando tar nativo..." -ForegroundColor DarkGray
tar -xf $ArchivePath -C $DestinationPath
}
# Verificar se 7-Zip está instalado como fallback
elseif (Test-Path "$env:ProgramFiles\7-Zip\7z.exe") {
Write-Host "📦 Extraindo usando 7-Zip..." -ForegroundColor DarkGray
$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"
# Extrair o arquivo .gz para um arquivo .tar temporário
$tarFile = [System.IO.Path]::ChangeExtension($ArchivePath, "tar")
& $7zipPath x $ArchivePath -o"$(Split-Path $ArchivePath)" -y | Out-Null
# Extrair o arquivo .tar para o destino
& $7zipPath x $tarFile -o"$DestinationPath" -y | Out-Null
# Remover o arquivo .tar temporário
if (Test-Path $tarFile) {
Remove-Item $tarFile -Force
}
}
else {
throw "Não foi possível encontrar uma ferramenta para extrair arquivos tar.gz. Instale o 7-Zip ou use Windows 10+ com suporte nativo a tar."
}
return $true
}
catch {
Write-Host "❌ Erro ao extrair arquivo tar.gz: $_" -ForegroundColor Red
return $false
}
}
<#
.SYNOPSIS
Copia o pacote para o destino final.
.DESCRIPTION
Copia o pacote para o destino final, identificando o diretório raiz da extração e copiando todos os arquivos para o destino.
.EXAMPLE
PS C:\> Copy-Package -SourceDir "C:\temp\extracted_package" -DestinationDir "C:\tools" -packageName "jdk8u452-b09"
#>
function Copy-Package {
param (
[string]$SourceDir,
[string]$DestinationDir,
[string]$packageName
)
try {
Write-Host "🚆 Movendo $packageName para destino final..." -ForegroundColor Yellow
# Identificar o diretório raiz da extração
$extractedDirs = Get-ChildItem -Path $SourceDir -Directory
# Criar o diretório de destino se não existir
if (-not (Test-Path $DestinationDir)) {
New-Item -ItemType Directory -Path $DestinationDir -Force | Out-Null
}
if ($extractedDirs.Count -eq 1) {
# Caso comum: um único diretório raiz dentro do arquivo
$contentSourceDir = $extractedDirs[0].FullName
Get-ChildItem -Path $contentSourceDir | Copy-Item -Destination $DestinationDir -Recurse -Force
}
else {
# Vários diretórios ou arquivos no nível raiz
Get-ChildItem -Path $SourceDir | Copy-Item -Destination $DestinationDir -Recurse -Force
}
# Verificar se a instalação foi bem-sucedida
if (-not (Test-Path $DestinationDir) -or (Get-ChildItem -Path $DestinationDir).Count -eq 0) {
throw "Instalação falhou: O diretório de destino está vazio ou não existe."
}
return $true
}
catch {
Write-Host "❌ Erro ao copiar para destino final: $_" -ForegroundColor Red
return $false
}
}
function Export-Package {
param (
[string]$PackagePath,
[string]$Destination
)
Write-Verbose "Extraindo pacote: $PackagePath"
# Ensure destination exists
if (-not (Test-Path -Path $Destination)) {
New-Item -ItemType Directory -Path $Destination -Force | Out-Null
}
if (-not (Test-Path -Path $PackagePath)) {
throw "Pacote não encontrado em: $PackagePath"
}
# Extract the zip file
Expand-Archive -Path $PackagePath -DestinationPath $Destination -Force
Write-Verbose "Pacote extraído com sucesso para: $Destination"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment