Skip to content

Instantly share code, notes, and snippets.

@guinetik
Created September 23, 2025 08:01
Show Gist options
  • Select an option

  • Save guinetik/1742147bc2a7d94c1c8970cc314543e7 to your computer and use it in GitHub Desktop.

Select an option

Save guinetik/1742147bc2a7d94c1c8970cc314543e7 to your computer and use it in GitHub Desktop.
# Script de Automação Desktop - Versão Simplificada e Funcional
param(
[string]$AppName,
[int]$TestDuration = 60
)
# Inicialização dos assemblies necessários
Write-Host "🔄 Inicializando componentes..." -ForegroundColor Cyan
try {
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName Microsoft.VisualBasic
Write-Host "✅ Assemblies carregados com sucesso!" -ForegroundColor Green
} catch {
Write-Host "❌ Erro ao carregar assemblies: $_" -ForegroundColor Red
Write-Host "💡 Tentando continuar com funcionalidade limitada..." -ForegroundColor Yellow
}
# Classe principal de automação usando apenas métodos nativos
class DesktopAutomation {
[string]$AppName
[int]$TestDuration
[System.Diagnostics.Process]$AppProcess
DesktopAutomation([string]$appName, [int]$testDuration) {
$this.AppName = $appName
$this.TestDuration = $testDuration
}
# Método simplificado para focar aplicativo
[bool]FocusApplication() {
try {
if (-not $this.AppProcess) {
$processes = Get-Process -Name $this.AppName -ErrorAction SilentlyContinue
if ($processes) {
$this.AppProcess = $processes[0]
} else {
Write-Host "⚠️ Processo não encontrado: $($this.AppName)" -ForegroundColor Yellow
return $false
}
}
# Usar método Microsoft.VisualBasic (mais confiável)
[Microsoft.VisualBasic.Interaction]::AppActivate($this.AppProcess.Id)
Write-Host "✅ Aplicativo focado: $($this.AppProcess.ProcessName) (PID: $($this.AppProcess.Id))" -ForegroundColor Green
Start-Sleep -Seconds 2
return $true
} catch {
Write-Host "⚠️ Não foi possível focar o aplicativo: $_" -ForegroundColor Yellow
Write-Host "💡 Continuando teste na janela ativa atual..." -ForegroundColor Cyan
return $false
}
}
# Iniciar aplicativo
[bool]StartApplication() {
try {
Write-Host "🚀 Iniciando aplicativo: $($this.AppName)" -ForegroundColor Yellow
# Verificar se já está executando
$existingProcess = Get-Process -Name $this.AppName -ErrorAction SilentlyContinue | Select-Object -First 1
if ($existingProcess) {
$this.AppProcess = $existingProcess
Write-Host "✅ Aplicativo já em execução (PID: $($this.AppProcess.Id))" -ForegroundColor Green
return $true
}
# Tentar iniciar o aplicativo
$appPaths = @(
$this.AppName,
"$($this.AppName).exe",
"C:\Windows\System32\$($this.AppName).exe",
"C:\Windows\SysWOW64\$($this.AppName).exe"
)
foreach ($path in $appPaths) {
try {
Write-Host "🔍 Tentando: $path" -ForegroundColor Gray
$this.AppProcess = Start-Process -FilePath $path -PassThru -ErrorAction Stop
if ($this.AppProcess) {
Write-Host "✅ Aplicativo iniciado com sucesso! (PID: $($this.AppProcess.Id))" -ForegroundColor Green
Start-Sleep -Seconds 3 # Aguardar carregar
return $true
}
} catch {
continue # Tentar próximo caminho
}
}
Write-Host "❌ Não foi possível iniciar '$($this.AppName)'" -ForegroundColor Red
Write-Host "💡 O teste continuará na janela ativa atual" -ForegroundColor Cyan
return $false
} catch {
Write-Host "❌ Erro ao iniciar aplicativo: $_" -ForegroundColor Red
return $false
}
}
# Método robusto para envio de texto
[void]SendText([string]$text) {
try {
# Tentar enviar o texto usando SendKeys
[System.Windows.Forms.SendKeys]::SendWait($text)
} catch {
Write-Host "⚠️ Erro ao enviar texto: '$text' - $_" -ForegroundColor Yellow
# Em caso de erro, continuar sem interromper o teste
}
}
# Enviar tecla especial
[void]SendSpecialKey([string]$key) {
try {
[System.Windows.Forms.SendKeys]::SendWait($key)
} catch {
Write-Host "⚠️ Erro ao enviar tecla especial: '$key'" -ForegroundColor Yellow
}
}
# Monkey Typing - digitação aleatória
[void]SimulateMonkeyTyping([int]$durationSeconds) {
Write-Host "🐒 === MONKEY TYPING POR $durationSeconds SEGUNDOS ===" -ForegroundColor Cyan
Write-Host "📝 Iniciando digitação aleatória..." -ForegroundColor Yellow
$startTime = Get-Date
$totalKeys = 0
$errorCount = 0
# Caracteres seguros para digitação
$characters = @(
# Letras minúsculas
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
# Letras maiúsculas
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
# Números
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
# Espaços e pontuação básica
' ', '.', ',', '!', '?', ':', ';'
)
$specialActions = @(
@{Name = "Backspace"; Key = "{BACKSPACE}"; Weight = 10},
@{Name = "Enter"; Key = "{ENTER}"; Weight = 5},
@{Name = "Tab"; Key = "{TAB}"; Weight = 3}
)
while (((Get-Date) - $startTime).TotalSeconds -lt $durationSeconds) {
try {
$action = Get-Random -Maximum 100
if ($action -lt 80) {
# 80% chance: digitar caractere normal
$char = $characters | Get-Random
$this.SendText($char)
$totalKeys++
} elseif ($action -lt 95) {
# 15% chance: ação especial
$specialAction = $specialActions | Get-Random
$this.SendSpecialKey($specialAction.Key)
Write-Host " 🔄 $($specialAction.Name)" -ForegroundColor DarkGray
$totalKeys++
} else {
# 5% chance: palavra aleatória
$words = @("hello", "world", "test", "automation", "script", "powershell", "windows", "public", "static", "final", "class", "extends", "for", "package", "npm", "nvm", "mvn", "install", "pack", "compose")
$word = $words | Get-Random
$this.SendText($word)
$totalKeys += $word.Length
}
# Delay aleatório (simular velocidade humana)
$delay = Get-Random -Minimum 50 -Maximum 300
Start-Sleep -Milliseconds $delay
# Mostrar progresso a cada 100 teclas
if ($totalKeys % 100 -eq 0 -and $totalKeys -gt 0) {
$elapsed = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
$remaining = [math]::Round($durationSeconds - $elapsed, 1)
$speed = [math]::Round($totalKeys / $elapsed, 1)
Write-Host " 📊 Progresso: $totalKeys teclas | ${elapsed}s | ${remaining}s restantes | ${speed} teclas/s" -ForegroundColor Gray
}
} catch {
$errorCount++
if ($errorCount % 10 -eq 0) {
Write-Host " ⚠️ $errorCount erros encontrados (continuando...)" -ForegroundColor Yellow
}
Start-Sleep -Milliseconds 100
}
}
$finalTime = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
$avgSpeed = if ($finalTime -gt 0) { [math]::Round($totalKeys / $finalTime, 1) } else { 0 }
Write-Host "✅ MONKEY TYPING CONCLUÍDO!" -ForegroundColor Green
Write-Host "📈 Estatísticas:" -ForegroundColor Cyan
Write-Host " • Total de teclas: $totalKeys" -ForegroundColor White
Write-Host " • Tempo: ${finalTime} segundos" -ForegroundColor White
Write-Host " • Velocidade média: $avgSpeed teclas/segundo" -ForegroundColor White
Write-Host " • Erros: $errorCount" -ForegroundColor White
}
# Movimentos de mouse
[void]SimulateMouseMovements([int]$durationSeconds) {
Write-Host "🖱️ === MOVIMENTOS DE MOUSE POR $durationSeconds SEGUNDOS ===" -ForegroundColor Magenta
$startTime = Get-Date
$movements = 0
$clicks = 0
# Obter dimensões da tela
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$screenWidth = $screen.Width
$screenHeight = $screen.Height
$margin = 50
Write-Host "📺 Resolução da tela: ${screenWidth}x${screenHeight}" -ForegroundColor Gray
Write-Host "🎯 Área de movimento: ${margin}px de margem" -ForegroundColor Gray
while (((Get-Date) - $startTime).TotalSeconds -lt $durationSeconds) {
try {
# Gerar posição aleatória
$x = Get-Random -Minimum $margin -Maximum ($screenWidth - $margin)
$y = Get-Random -Minimum $margin -Maximum ($screenHeight - $margin)
# Mover mouse
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
$movements++
# Chance de clique (8% das vezes)
if ((Get-Random -Maximum 100) -lt 8) {
# Simular clique usando método nativo do .NET
# Nota: Em ambiente real, isso pode não funcionar perfeitamente
# mas serve para demonstração
Write-Host " 🎯 Click simulado em ($x, $y)" -ForegroundColor DarkYellow
$clicks++
Start-Sleep -Milliseconds 200
}
# Delay aleatório entre movimentos
$delay = Get-Random -Minimum 150 -Maximum 600
Start-Sleep -Milliseconds $delay
# Progresso a cada 25 movimentos
if ($movements % 25 -eq 0) {
$elapsed = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
$remaining = [math]::Round($durationSeconds - $elapsed, 1)
Write-Host " 📊 $movements movimentos | $clicks clicks | ${remaining}s restantes" -ForegroundColor Gray
}
} catch {
Write-Host " ⚠️ Erro no movimento do mouse" -ForegroundColor Yellow
Start-Sleep -Milliseconds 200
}
}
$finalTime = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
Write-Host "✅ MOVIMENTOS CONCLUÍDOS!" -ForegroundColor Green
Write-Host "📈 Estatísticas:" -ForegroundColor Cyan
Write-Host " • Movimentos: $movements" -ForegroundColor White
Write-Host " • Clicks: $clicks" -ForegroundColor White
Write-Host " • Tempo: ${finalTime} segundos" -ForegroundColor White
}
# Atalhos de teclado
[void]SimulateKeyboardShortcuts([int]$count) {
Write-Host "⌨️ === SIMULANDO $count ATALHOS DE TECLADO ===" -ForegroundColor Yellow
# Atalhos comuns e seguros
$shortcuts = @(
@{Name = "Ctrl+A (Selecionar Tudo)"; Keys = "^a"; Safe = $true},
@{Name = "Ctrl+C (Copiar)"; Keys = "^c"; Safe = $true},
@{Name = "Ctrl+V (Colar)"; Keys = "^v"; Safe = $false}, # Pode colar conteúdo indesejado
@{Name = "Ctrl+Z (Desfazer)"; Keys = "^z"; Safe = $true},
@{Name = "Ctrl+S (Salvar)"; Keys = "^s"; Safe = $false}, # Pode salvar sobre arquivo
@{Name = "Ctrl+F (Buscar)"; Keys = "^f"; Safe = $true},
@{Name = "Enter"; Keys = "{ENTER}"; Safe = $true},
@{Name = "Tab"; Keys = "{TAB}"; Safe = $true},
@{Name = "Escape"; Keys = "{ESC}"; Safe = $true},
@{Name = "Seta para Direita"; Keys = "{RIGHT}"; Safe = $true},
@{Name = "Seta para Esquerda"; Keys = "{LEFT}"; Safe = $true},
@{Name = "Home"; Keys = "{HOME}"; Safe = $true},
@{Name = "End"; Keys = "{END}"; Safe = $true}
)
# Filtrar apenas atalhos seguros para evitar problemas
$safeShortcuts = $shortcuts | Where-Object { $_.Safe -eq $true }
for ($i = 1; $i -le $count; $i++) {
try {
$shortcut = $safeShortcuts | Get-Random
Write-Host " ⚡ [$i/$count] $($shortcut.Name)" -ForegroundColor Gray
$this.SendSpecialKey($shortcut.Keys)
# Delay entre atalhos
Start-Sleep -Milliseconds (Get-Random -Minimum 500 -Maximum 1200)
} catch {
Write-Host " ❌ Erro ao executar atalho: $_" -ForegroundColor Red
Start-Sleep -Milliseconds 500
}
}
Write-Host "✅ Atalhos de teclado concluídos!" -ForegroundColor Green
}
# Teste completo
[void]RunCompleteTest() {
$border = "=" * 60
Write-Host $border -ForegroundColor Blue
Write-Host "🤖 INICIANDO AUTOMAÇÃO DESKTOP COMPLETA" -ForegroundColor White -BackgroundColor Blue
Write-Host $border -ForegroundColor Blue
Write-Host ""
Write-Host "📋 Configuração do Teste:" -ForegroundColor Cyan
Write-Host " • Aplicativo alvo: $($this.AppName)" -ForegroundColor White
Write-Host " • Duração total: $($this.TestDuration) segundos" -ForegroundColor White
Write-Host " • Início: $(Get-Date -Format 'HH:mm:ss')" -ForegroundColor White
Write-Host ""
$overallStart = Get-Date
# Fase 1: Inicializar aplicativo
Write-Host "🚀 FASE 1: Inicialização do Aplicativo" -ForegroundColor Yellow
$appStarted = $this.StartApplication()
if ($appStarted) {
Write-Host "🎯 FASE 2: Focando Aplicativo" -ForegroundColor Yellow
$this.FocusApplication()
} else {
Write-Host "⚠️ Continuando teste na janela ativa..." -ForegroundColor Yellow
}
Write-Host ""
# Fase 3: Sequência de testes
Write-Host "🎮 FASE 3: Executando Testes de Automação" -ForegroundColor Yellow
Write-Host "`n📝 Teste 1: Atalhos Iniciais"
$this.SimulateKeyboardShortcuts(4)
Write-Host "`n🐒 Teste 2: Monkey Typing (Fase 1)"
$this.SimulateMonkeyTyping(120)
Write-Host "`n🖱️ Teste 3: Movimentos de Mouse"
$this.SimulateMouseMovements(60)
Write-Host "`n⌨️ Teste 4: Atalhos Intermediários"
$this.SimulateKeyboardShortcuts(3)
Write-Host "`n🐒 Teste 5: Monkey Typing (Fase 2)"
$this.SimulateMonkeyTyping(120)
# Resultado final
$totalDuration = [math]::Round(((Get-Date) - $overallStart).TotalSeconds, 2)
Write-Host ""
Write-Host $border -ForegroundColor Green
Write-Host "🎉 AUTOMAÇÃO CONCLUÍDA COM SUCESSO!" -ForegroundColor White -BackgroundColor Green
Write-Host $border -ForegroundColor Green
Write-Host "📊 Relatório Final:" -ForegroundColor Cyan
Write-Host " • Tempo total: $totalDuration segundos" -ForegroundColor White
Write-Host " • Aplicativo: $($this.AppName)" -ForegroundColor White
Write-Host " • Status: ✅ Completo" -ForegroundColor White
Write-Host " • Finalizado em: $(Get-Date -Format 'HH:mm:ss')" -ForegroundColor White
Write-Host ""
}
}
# Funções auxiliares
function Start-DesktopAutomationTest {
param(
[string]$AppName = "notepad",
[int]$TestDuration = 60
)
$automator = [DesktopAutomation]::new($AppName, $TestDuration)
$automator.RunCompleteTest()
}
function Test-MonkeyTyping {
param([int]$Seconds = 30)
Write-Host "🐒 TESTE RÁPIDO: MONKEY TYPING" -ForegroundColor Yellow
$automator = [DesktopAutomation]::new("notepad", $Seconds)
$automator.StartApplication()
$automator.FocusApplication()
$automator.SimulateMonkeyTyping($Seconds)
}
function Test-MouseMovements {
param([int]$Seconds = 20)
Write-Host "🖱️ TESTE RÁPIDO: MOVIMENTOS DE MOUSE" -ForegroundColor Yellow
$automator = [DesktopAutomation]::new("", $Seconds)
$automator.SimulateMouseMovements($Seconds)
}
function Test-KeyboardShortcuts {
param([int]$Count = 10)
Write-Host "⌨️ TESTE RÁPIDO: ATALHOS DE TECLADO" -ForegroundColor Yellow
$automator = [DesktopAutomation]::new("", 0)
$automator.SimulateKeyboardShortcuts($Count)
}
function Show-Menu {
Clear-Host
$title = "🤖 AUTOMAÇÃO DESKTOP - MENU PRINCIPAL"
$border = "=" * $title.Length
Write-Host $border -ForegroundColor Cyan
Write-Host $title -ForegroundColor Cyan
Write-Host $border -ForegroundColor Cyan
Write-Host ""
Write-Host "Escolha uma opção:" -ForegroundColor Yellow
Write-Host ""
Write-Host " 1️⃣ Teste Completo (Notepad)" -ForegroundColor White
Write-Host " 2️⃣ Apenas Monkey Typing" -ForegroundColor White
Write-Host " 3️⃣ Apenas Movimentos de Mouse" -ForegroundColor White
Write-Host " 4️⃣ Apenas Atalhos de Teclado" -ForegroundColor White
Write-Host " 5️⃣ Teste com Aplicativo Personalizado" -ForegroundColor White
Write-Host " 6️⃣ Sair" -ForegroundColor Red
Write-Host ""
}
function Show-Countdown {
param([int]$Seconds = 3)
Write-Host "⏰ Iniciando em:" -ForegroundColor Yellow
for ($i = $Seconds; $i -gt 0; $i--) {
Write-Host " $i..." -ForegroundColor Yellow -NoNewline
Start-Sleep -Seconds 1
Write-Host " ✓" -ForegroundColor Green
}
Write-Host " 🚀 INICIANDO AGORA!" -ForegroundColor Green
Write-Host ""
}
# === EXECUÇÃO PRINCIPAL ===
Write-Host "🔧 Inicializando Sistema de Automação Desktop..." -ForegroundColor Cyan
Start-Sleep -Seconds 1
# Verificar se foi chamado com parâmetros (linha de comando)
if ($PSBoundParameters.Count -gt 0 -and $AppName) {
Write-Host "📟 Modo: Linha de Comando" -ForegroundColor Gray
Write-Host "🎯 Aplicativo: $AppName" -ForegroundColor Gray
Write-Host "⏱️ Duração: $TestDuration segundos" -ForegroundColor Gray
Write-Host ""
Show-Countdown -Seconds 3
Start-DesktopAutomationTest -AppName $AppName -TestDuration $TestDuration
} else {
# Modo interativo com menu
Write-Host "📟 Modo: Interativo" -ForegroundColor Gray
Write-Host ""
do {
Show-Menu
$choice = Read-Host "Digite sua opção (1-6)"
switch ($choice) {
'1' {
Write-Host "`n🚀 INICIANDO TESTE COMPLETO COM NOTEPAD..." -ForegroundColor Green
Show-Countdown -Seconds 5
Start-DesktopAutomationTest -AppName "notepad" -TestDuration 50
Write-Host "`n✨ Teste concluído! Pressione qualquer tecla para voltar ao menu..." -ForegroundColor Green
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
'2' {
Write-Host "`n🐒 INICIANDO MONKEY TYPING..." -ForegroundColor Green
Show-Countdown -Seconds 3
Test-MonkeyTyping -Seconds 30
Write-Host "`n✨ Teste concluído! Pressione qualquer tecla para voltar ao menu..." -ForegroundColor Green
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
'3' {
Write-Host "`n🖱️ INICIANDO MOVIMENTOS DE MOUSE..." -ForegroundColor Green
Test-MouseMovements -Seconds 25
Write-Host "`n✨ Teste concluído! Pressione qualquer tecla para voltar ao menu..." -ForegroundColor Green
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
'4' {
Write-Host "`n⌨️ INICIANDO ATALHOS DE TECLADO..." -ForegroundColor Green
Test-KeyboardShortcuts -Count 12
Write-Host "`n✨ Teste concluído! Pressione qualquer tecla para voltar ao menu..." -ForegroundColor Green
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
'5' {
Write-Host ""
$customApp = Read-Host "📱 Digite o nome do aplicativo (ex: calc, chrome, code)"
$customDuration = Read-Host "⏱️ Digite a duração em segundos"
if ($customApp -and $customDuration) {
Write-Host "`n🚀 INICIANDO TESTE PERSONALIZADO..." -ForegroundColor Green
Show-Countdown -Seconds 3
Start-DesktopAutomationTest -AppName $customApp -TestDuration $customDuration
} else {
Write-Host "❌ Parâmetros inválidos!" -ForegroundColor Red
}
Write-Host "`n✨ Teste concluído! Pressione qualquer tecla para voltar ao menu..." -ForegroundColor Green
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
'6' {
Write-Host "`n👋 Encerrando sistema..." -ForegroundColor Green
Write-Host "Obrigado por usar a Automação Desktop!" -ForegroundColor Cyan
Start-Sleep -Seconds 2
exit 0
}
default {
Write-Host "`n❌ Opção inválida! Por favor, escolha um número de 1 a 6." -ForegroundColor Red
Start-Sleep -Seconds 2
}
}
} while ($true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment