Last active
November 21, 2025 13:58
-
-
Save joaohcrangel/ef7c83efaaca5846b691d215834d44bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # ============================================ | |
| # Script de Configuração Pós-Formatação do Windows | |
| # ============================================ | |
| # Este script automatiza a instalação de aplicativos e configurações essenciais | |
| # após a formatação do PC, incluindo ferramentas de desenvolvimento e produtividade | |
| # Requer execução como Administrador | |
| #Requires -RunAsAdministrator | |
| # Solicita o nome do PC para identificação da chave SSH | |
| $pcName = Read-Host "Digite o nome do PC" | |
| # Define a política de execução para permitir scripts locais (necessário para o script funcionar) | |
| Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force | |
| # Tenta registrar o App Installer (Winget) se já estiver presente no sistema | |
| try { | |
| Add-AppxPackage -RegisterByFamilyName -MainPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe -ErrorAction SilentlyContinue | |
| } catch { | |
| Write-Warning "Não foi possível registrar o App Installer automaticamente." | |
| } | |
| # ============================================ | |
| # FUNÇÕES AUXILIARES | |
| # ============================================ | |
| # Função para verificar e instalar o Winget (gerenciador de pacotes do Windows) | |
| function Enable-Winget { | |
| # Verifica se o comando winget está disponível no sistema | |
| if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { | |
| Write-Output "⚙️ Winget não está instalado. Iniciando instalação..." | |
| # Desabilita a barra de progresso para downloads mais rápidos | |
| $progressPreference = 'silentlyContinue' | |
| # Define o diretório temporário para downloads | |
| $tempDir = Join-Path $env:TEMP "WingetInstall" | |
| New-Item -ItemType Directory -Path $tempDir -Force | Out-Null | |
| Set-Location $tempDir | |
| try { | |
| Write-Output "📥 Baixando Winget e suas dependências..." | |
| # Baixa o instalador do Winget (App Installer) | |
| Invoke-WebRequest -Uri https://aka.ms/getwinget -OutFile "Microsoft.DesktopAppInstaller.msixbundle" | |
| # Baixa as bibliotecas C++ necessárias para o Winget funcionar | |
| Invoke-WebRequest -Uri https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx -OutFile "Microsoft.VCLibs.x64.14.00.Desktop.appx" | |
| # Baixa a biblioteca UI.Xaml necessária para a interface do Winget | |
| Invoke-WebRequest -Uri https://github.com/microsoft/microsoft-ui-xaml/releases/download/v2.8.6/Microsoft.UI.Xaml.2.8.x64.appx -OutFile "Microsoft.UI.Xaml.2.8.x64.appx" | |
| Write-Output "📦 Instalando dependências..." | |
| # Instala as bibliotecas na ordem correta | |
| Add-AppxPackage "Microsoft.VCLibs.x64.14.00.Desktop.appx" | |
| Add-AppxPackage "Microsoft.UI.Xaml.2.8.x64.appx" | |
| Add-AppxPackage "Microsoft.DesktopAppInstaller.msixbundle" | |
| Write-Output "✅ Winget instalado com sucesso!" | |
| } catch { | |
| Write-Error "❌ Erro ao instalar o Winget: $_" | |
| throw | |
| } finally { | |
| # Limpa os arquivos temporários | |
| Set-Location $env:TEMP | |
| Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue | |
| } | |
| } else { | |
| Write-Output "✅ Winget já está instalado." | |
| } | |
| } | |
| # Função para habilitar o WSL (Windows Subsystem for Linux) | |
| # Permite executar distribuições Linux nativamente no Windows | |
| function Enable-WSL { | |
| Write-Output "🔍 Verificando WSL..." | |
| # Verifica se o recurso WSL já está habilitado | |
| $wslEnabled = (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux).State -eq "Enabled" | |
| if (-not $wslEnabled) { | |
| Write-Output "⚙️ Habilitando WSL (Windows Subsystem for Linux)..." | |
| try { | |
| # Habilita o recurso WSL sem forçar reinicialização imediata | |
| Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart -All | |
| # Habilita também a Plataforma de Máquina Virtual (necessária para WSL 2) | |
| Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -NoRestart -All | |
| Write-Output "✅ WSL habilitado com sucesso!" | |
| } catch { | |
| Write-Warning "⚠️ Não foi possível habilitar o WSL: $_" | |
| } | |
| } else { | |
| Write-Output "✅ WSL já está habilitado." | |
| } | |
| } | |
| # Função para habilitar o Hyper-V (plataforma de virtualização da Microsoft) | |
| # Necessário para Docker Desktop e outras ferramentas de virtualização | |
| function Enable-HyperV { | |
| Write-Output "🔍 Verificando Hyper-V..." | |
| # Verifica se o Hyper-V já está habilitado | |
| $hyperVEnabled = (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All).State -eq "Enabled" | |
| if (-not $hyperVEnabled) { | |
| Write-Output "⚙️ Habilitando Hyper-V (necessário para Docker e virtualização)..." | |
| try { | |
| # Habilita todos os componentes do Hyper-V sem forçar reinicialização imediata | |
| Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All -NoRestart -All | |
| Write-Output "✅ Hyper-V habilitado com sucesso!" | |
| } catch { | |
| Write-Warning "⚠️ Não foi possível habilitar o Hyper-V. Verifique se sua CPU suporta virtualização: $_" | |
| } | |
| } else { | |
| Write-Output "✅ Hyper-V já está habilitado." | |
| } | |
| } | |
| # Função para verificar se há reinicialização pendente no sistema | |
| function Test-PendingReboot { | |
| # Verifica a chave do registro que indica se há componentes aguardando reinicialização | |
| $cbsReboot = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -ErrorAction SilentlyContinue | |
| $wuReboot = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue | |
| return ($cbsReboot -ne $null) -or ($wuReboot -ne $null) | |
| } | |
| # Função para instalar aplicativos via Winget com tratamento de erros | |
| function Install-WingetApp { | |
| param( | |
| [string]$AppId, | |
| [string]$AppName, | |
| [string]$Override = "" | |
| ) | |
| Write-Output "📦 Instalando $AppName..." | |
| try { | |
| if ($Override) { | |
| # Instala com parâmetros personalizados (override) | |
| winget install --id $AppId -e --accept-package-agreements --accept-source-agreements --override $Override --silent | |
| } else { | |
| # Instala com configurações padrão | |
| winget install --id $AppId -e --accept-package-agreements --accept-source-agreements --silent | |
| } | |
| Write-Output " ✅ $AppName instalado!" | |
| } catch { | |
| Write-Warning " ⚠️ Erro ao instalar $AppName : $_" | |
| } | |
| } | |
| # ============================================ | |
| # INÍCIO DA EXECUÇÃO PRINCIPAL | |
| # ============================================ | |
| Write-Output "`n🚀 Iniciando configuração do sistema...`n" | |
| # Habilita os recursos essenciais do Windows | |
| Enable-Winget | |
| Enable-WSL | |
| Enable-HyperV | |
| # Verifica se há reinicialização pendente após habilitar recursos | |
| if (Test-PendingReboot) { | |
| Write-Output "`n⚠️ ATENÇÃO: Uma reinicialização é necessária para aplicar as alterações." | |
| Write-Output "Por favor, reinicie o computador e execute este script novamente para continuar a instalação dos aplicativos.`n" | |
| $response = Read-Host "Deseja reiniciar agora? (S/N)" | |
| if ($response -eq 'S' -or $response -eq 's') { | |
| Write-Output "🔄 Reiniciando o sistema..." | |
| Restart-Computer -Force | |
| exit | |
| } else { | |
| Write-Output "❌ Instalação cancelada. Execute o script novamente após reiniciar.`n" | |
| exit | |
| } | |
| } | |
| Write-Output "`n📦 Iniciando instalação de aplicativos...`n" | |
| # ============================================ | |
| # NAVEGADORES | |
| # ============================================ | |
| Install-WingetApp -AppId "Google.Chrome" -AppName "Google Chrome" | |
| # ============================================ | |
| # FERRAMENTAS DE DESENVOLVIMENTO | |
| # ============================================ | |
| Install-WingetApp -AppId "Git.Git" -AppName "Git (controle de versão)" | |
| Install-WingetApp -AppId "GitHub.cli" -AppName "GitHub CLI" | |
| Install-WingetApp -AppId "Microsoft.VisualStudioCode" -AppName "Visual Studio Code" -Override "/SILENT /mergetasks=!runcode,addcontextmenufiles,addcontextmenufolders" | |
| Install-WingetApp -AppId "Microsoft.WindowsTerminal" -AppName "Windows Terminal" | |
| Install-WingetApp -AppId "Microsoft.PowerShell" -AppName "PowerShell 7" | |
| Install-WingetApp -AppId "Postman.Postman" -AppName "Postman (testes de API)" | |
| # ============================================ | |
| # BANCO DE DADOS | |
| # ============================================ | |
| Install-WingetApp -AppId "DBeaver.DBeaver" -AppName "DBeaver (cliente universal de BD)" | |
| # ============================================ | |
| # CONTAINERIZAÇÃO E VIRTUALIZAÇÃO | |
| # ============================================ | |
| Install-WingetApp -AppId "Docker.DockerDesktop" -AppName "Docker Desktop" | |
| # ============================================ | |
| # LINGUAGENS DE PROGRAMAÇÃO E RUNTIMES | |
| # ============================================ | |
| Install-WingetApp -AppId "CoreyButler.NVMforWindows" -AppName "NVM for Windows" | |
| # Instala Node.js LTS usando NVM | |
| $env:NVM_HOME = "$env:ProgramFiles\nvm" | |
| $env:NVM_SYMLINK = "$env:ProgramFiles\nodejs" | |
| $env:Path += ";$env:NVM_HOME;$env:NVM_SYMLINK" | |
| Write-Output "📦 Instalando Node.js LTS via NVM..." | |
| nvm install lts | |
| nvm use lts | |
| Write-Output "✅ Node.js LTS instalado e selecionado via NVM!" | |
| Install-WingetApp -AppId "Python.Python.3" -AppName "Python 3" | |
| Install-WingetApp -AppId "Rustlang.Rustup" -AppName "Rust" | |
| Install-WingetApp -AppId "GoLang.Go" -AppName "Go Lang" | |
| # ============================================ | |
| # IDEs E EDITORES | |
| # ============================================ | |
| Install-WingetApp -AppId "Google.AndroidStudio" -AppName "Android Studio" | |
| Install-WingetApp -AppId "Microsoft.VisualStudio.2022.Community" -AppName "Visual Studio 2022 Community" | |
| # ============================================ | |
| # FERRAMENTAS DE DESIGN | |
| # ============================================ | |
| Install-WingetApp -AppId "Figma.Figma" -AppName "Figma Desktop" | |
| # ============================================ | |
| # CLOUD E DEVOPS | |
| # ============================================ | |
| Install-WingetApp -AppId "Hashicorp.Terraform" -AppName "Terraform (Infrastructure as Code)" | |
| Install-WingetApp -AppId "Microsoft.AzureCLI" -AppName "Azure CLI" | |
| Install-WingetApp -AppId "Amazon.AWSCLI" -AppName "AWS CLI" | |
| Install-WingetApp -AppId "Kubernetes.kubectl" -AppName "kubectl (Kubernetes)" | |
| Install-WingetApp -AppId "Helm.Helm" -AppName "Helm (gerenciador de pacotes K8s)" | |
| Install-WingetApp -AppId "DigitalOcean.Doctl" -AppName "doctl (DigitalOcean CLI)" | |
| # ============================================ | |
| # COMUNICAÇÃO | |
| # ============================================ | |
| Install-WingetApp -AppId "WhatsApp.WhatsApp" -AppName "WhatsApp Desktop" | |
| Install-WingetApp -AppId "Zoom.Zoom" -AppName "Zoom" | |
| Install-WingetApp -AppId "Microsoft.Teams" -AppName "Microsoft Teams" | |
| # ============================================ | |
| # UTILIDADES | |
| # ============================================ | |
| Install-WingetApp -AppId "Microsoft.PowerToys" -AppName "PowerToys (utilitários Windows)" | |
| Install-WingetApp -AppId "DominikReichl.KeePass" -AppName "KeePass (gerenciador de senhas)" | |
| Install-WingetApp -AppId "RARLab.WinRAR" -AppName "WinRAR (compactador)" | |
| Install-WingetApp -AppId "OBSProject.OBSStudio" -AppName "OBS Studio (gravação de tela)" | |
| # ============================================ | |
| # ENTRETENIMENTO | |
| # ============================================ | |
| Install-WingetApp -AppId "9WZDNCRFJ3B4" -AppName "JW Library" | |
| Write-Output "`n✅ Todos os aplicativos foram instalados!`n" | |
| # ============================================ | |
| # CONFIGURAÇÃO GIT E GITHUB | |
| # ============================================ | |
| Write-Output "🔑 Configurando chave SSH para GitHub...`n" | |
| # Define o diretório SSH no perfil do usuário | |
| $sshDir = Join-Path $env:USERPROFILE ".ssh" | |
| $sshKeyPath = Join-Path $sshDir "id_ed25519" | |
| # Cria o diretório .ssh se não existir | |
| if (-not (Test-Path $sshDir)) { | |
| New-Item -ItemType Directory -Path $sshDir -Force | Out-Null | |
| } | |
| # Verifica se já existe uma chave SSH | |
| if (-not (Test-Path $sshKeyPath)) { | |
| Write-Output "📝 Gerando nova chave SSH..." | |
| # Gera a chave SSH usando o algoritmo ed25519 (mais seguro e moderno) | |
| # -t: tipo de chave (ed25519) | |
| # -C: comentário (identificação da chave) | |
| # -q: modo silencioso | |
| # -N: senha (vazia neste caso) | |
| # -f: caminho do arquivo | |
| ssh-keygen -t ed25519 -C "$pcName" -q -N '""' -f $sshKeyPath | |
| Write-Output "✅ Chave SSH gerada com sucesso!" | |
| } else { | |
| Write-Output "✅ Chave SSH já existe." | |
| } | |
| # Lê o conteúdo da chave pública SSH gerada | |
| $publicKey = Get-Content "$sshKeyPath.pub" | |
| Write-Output "`n🔐 Configurando autenticação GitHub...`n" | |
| # Verifica se o GitHub CLI está disponível | |
| if (Get-Command gh -ErrorAction SilentlyContinue) { | |
| try { | |
| # Inicia o processo de autenticação do GitHub CLI | |
| # O usuário será direcionado ao navegador para autorizar | |
| Write-Output "Por favor, siga as instruções no navegador para autenticar no GitHub." | |
| gh auth login | |
| Write-Output "`n📤 Adicionando chave SSH ao GitHub..." | |
| # Adiciona a chave SSH pública à conta GitHub usando o GitHub CLI | |
| # Usa echo para passar a chave via pipeline para evitar problemas com variáveis | |
| $publicKey | gh ssh-key add - --title "$pcName" --type "authentication" | |
| Write-Output "✅ Chave SSH adicionada ao GitHub com sucesso!" | |
| # Configura o nome de usuário Git (opcional, o usuário pode editar) | |
| Write-Output "`n⚙️ Configuração adicional do Git..." | |
| $gitName = Read-Host "Digite seu nome para commits Git (pressione Enter para pular)" | |
| if ($gitName) { | |
| git config --global user.name "$gitName" | |
| } | |
| # Configura o email do Git (opcional) | |
| $gitEmail = Read-Host "Digite seu email para commits Git (pressione Enter para pular)" | |
| if ($gitEmail) { | |
| git config --global user.email "$gitEmail" | |
| } | |
| } catch { | |
| Write-Warning "⚠️ Erro ao configurar GitHub: $_" | |
| Write-Output "`nVocê pode adicionar a chave SSH manualmente em: https://github.com/settings/keys" | |
| Write-Output "Chave pública:`n$publicKey" | |
| } | |
| } else { | |
| Write-Warning "⚠️ GitHub CLI não encontrado. Instale-o primeiro ou adicione a chave SSH manualmente." | |
| Write-Output "Chave pública SSH:`n$publicKey" | |
| } | |
| # ============================================ | |
| # FINALIZAÇÃO | |
| # ============================================ | |
| Write-Output "`n" + "="*50 | |
| Write-Output "🎉 CONFIGURAÇÃO CONCLUÍDA COM SUCESSO!" | |
| Write-Output "="*50 | |
| Write-Output "`n📋 Resumo:" | |
| Write-Output " ✅ Recursos do Windows habilitados (WSL, Hyper-V)" | |
| Write-Output " ✅ Aplicativos instalados via Winget" | |
| Write-Output " ✅ Chave SSH configurada" | |
| Write-Output " ✅ GitHub CLI autenticado" | |
| Write-Output "`n💡 Próximos passos recomendados:" | |
| Write-Output " 1. Reinicie o computador para garantir que todas as alterações sejam aplicadas" | |
| Write-Output " 2. Abra o Docker Desktop e faça o login" | |
| Write-Output " 3. Configure suas extensões do VS Code" | |
| Write-Output " 4. Teste a conexão SSH com: ssh -T git@github.com" | |
| Write-Output "`n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment