Skip to content

Instantly share code, notes, and snippets.

@guinetik
Created September 23, 2025 10:47
Show Gist options
  • Select an option

  • Save guinetik/17a530bcaab2053f63becca67667a1bd to your computer and use it in GitHub Desktop.

Select an option

Save guinetik/17a530bcaab2053f63becca67667a1bd to your computer and use it in GitHub Desktop.
# Automação Desktop - Versão Ultra Compatível
# Funciona mesmo sem .NET Framework completo
param(
[string]$AppName,
[int]$TestDuration = 60
)
Write-Host "🚀 === AUTOMAÇÃO DESKTOP ULTRA COMPATÍVEL ===" -ForegroundColor Cyan
Write-Host "💡 Esta versão usa apenas recursos nativos do Windows" -ForegroundColor Yellow
Write-Host ""
# Detectar qual método usar
$UseWScript = $false
$UseDotNet = $false
# Teste 1: Tentar .NET primeiro
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
$UseDotNet = $true
Write-Host "✅ Modo: .NET Framework disponível" -ForegroundColor Green
} catch {
Write-Host "⚠️ .NET Framework limitado, usando WScript.Shell" -ForegroundColor Yellow
$UseWScript = $true
}
Write-Host ""
class DesktopAutomationCompatible {
[string]$AppName
[int]$TestDuration
[System.Diagnostics.Process]$AppProcess
[object]$WShell
[bool]$UseDotNet
DesktopAutomationCompatible([string]$appName, [int]$testDuration, [bool]$useDotNet) {
$this.AppName = $appName
$this.TestDuration = $testDuration
$this.UseDotNet = $useDotNet
# Sempre criar WScript.Shell como fallback
try {
$this.WShell = New-Object -ComObject WScript.Shell
Write-Host "✅ WScript.Shell inicializado" -ForegroundColor Green
} catch {
Write-Host "❌ Erro ao inicializar WScript.Shell: $_" -ForegroundColor Red
}
}
# Método híbrido 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
}
}
# Método 1: Microsoft.VisualBasic (se disponível)
try {
Add-Type -AssemblyName Microsoft.VisualBasic -ErrorAction Stop
[Microsoft.VisualBasic.Interaction]::AppActivate($this.AppProcess.Id)
Write-Host "✅ Aplicativo focado via VisualBasic: $($this.AppProcess.ProcessName)" -ForegroundColor Green
Start-Sleep -Seconds 2
return $true
} catch {
Write-Host "⚠️ VisualBasic não disponível, tentando WScript..." -ForegroundColor Yellow
}
# Método 2: WScript.Shell AppActivate
try {
if ($this.WShell) {
$this.WShell.AppActivate($this.AppProcess.Id)
Write-Host "✅ Aplicativo focado via WScript: $($this.AppProcess.ProcessName)" -ForegroundColor Green
Start-Sleep -Seconds 2
return $true
}
} catch {
Write-Host "⚠️ WScript AppActivate falhou: $_" -ForegroundColor Yellow
}
# Método 3: Fallback - tentar focar pela janela
try {
$this.WShell.AppActivate($this.AppProcess.ProcessName)
Write-Host "✅ Aplicativo focado por nome: $($this.AppProcess.ProcessName)" -ForegroundColor Green
Start-Sleep -Seconds 2
return $true
} catch {
Write-Host "⚠️ Não foi possível focar o aplicativo" -ForegroundColor Yellow
return $false
}
} catch {
Write-Host "❌ Erro ao focar aplicativo: $_" -ForegroundColor Red
return $false
}
}
# Método para 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 usando diferentes métodos
$methods = @(
@{Name = "Direct"; Command = $this.AppName},
@{Name = "With .exe"; Command = "$($this.AppName).exe"},
@{Name = "System32"; Command = "C:\Windows\System32\$($this.AppName).exe"},
@{Name = "SysWOW64"; Command = "C:\Windows\SysWOW64\$($this.AppName).exe"}
)
foreach ($method in $methods) {
try {
Write-Host "🔍 Tentando $($method.Name): $($method.Command)" -ForegroundColor Gray
# Método 1: Start-Process
if (Test-Path $method.Command -ErrorAction SilentlyContinue) {
$this.AppProcess = Start-Process -FilePath $method.Command -PassThru -ErrorAction Stop
} else {
$this.AppProcess = Start-Process -FilePath $method.Command -PassThru -ErrorAction Stop
}
if ($this.AppProcess) {
Write-Host "✅ Aplicativo iniciado com sucesso! (PID: $($this.AppProcess.Id))" -ForegroundColor Green
Start-Sleep -Seconds 3
return $true
}
} catch {
continue
}
}
# Método alternativo: WScript.Shell Run
try {
Write-Host "🔍 Tentando WScript.Shell Run..." -ForegroundColor Gray
$this.WShell.Run($this.AppName, 1, $false)
Start-Sleep -Seconds 3
# Verificar se o processo foi criado
$newProcess = Get-Process -Name $this.AppName -ErrorAction SilentlyContinue | Select-Object -First 1
if ($newProcess) {
$this.AppProcess = $newProcess
Write-Host "✅ Aplicativo iniciado via WScript! (PID: $($this.AppProcess.Id))" -ForegroundColor Green
return $true
}
} catch {
Write-Host "⚠️ WScript Run falhou: $_" -ForegroundColor Yellow
}
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 híbrido para envio de texto
[void]SendText([string]$text) {
try {
if ($this.UseDotNet) {
# Tentar .NET primeiro
[System.Windows.Forms.SendKeys]::SendWait($text)
} else {
# Usar WScript.Shell
$this.WShell.SendKeys($text)
}
} catch {
# Fallback: WScript.Shell
try {
$this.WShell.SendKeys($text)
} catch {
Write-Host "⚠️ Erro ao enviar texto: '$text'" -ForegroundColor Yellow
}
}
}
# Enviar tecla especial
[void]SendSpecialKey([string]$key) {
try {
if ($this.UseDotNet) {
[System.Windows.Forms.SendKeys]::SendWait($key)
} else {
# Converter para formato WScript se necessário
$wscriptKey = $this.ConvertToWScriptKey($key)
$this.WShell.SendKeys($wscriptKey)
}
} catch {
try {
$wscriptKey = $this.ConvertToWScriptKey($key)
$this.WShell.SendKeys($wscriptKey)
} catch {
Write-Host "⚠️ Erro ao enviar tecla especial: '$key'" -ForegroundColor Yellow
}
}
}
# Converter teclas especiais para formato WScript
[string]ConvertToWScriptKey([string]$dotNetKey) {
$conversions = @{
'{ENTER}' = '~'
'{TAB}' = '{TAB}'
'{BACKSPACE}' = '{BS}'
'{ESC}' = '{ESC}'
'{DELETE}' = '{DELETE}'
'{HOME}' = '{HOME}'
'{END}' = '{END}'
'{LEFT}' = '{LEFT}'
'{RIGHT}' = '{RIGHT}'
'{UP}' = '{UP}'
'{DOWN}' = '{DOWN}'
'^a' = '^a'
'^c' = '^c'
'^v' = '^v'
'^z' = '^z'
'^s' = '^s'
'^f' = '^f'
}
if ($conversions.ContainsKey($dotNetKey)) {
return $conversions[$dotNetKey]
}
return $dotNetKey
}
# Monkey Typing usando método híbrido
[void]SimulateMonkeyTyping([int]$durationSeconds) {
Write-Host "🐒 === MONKEY TYPING POR $durationSeconds SEGUNDOS ===" -ForegroundColor Cyan
Write-Host "📝 Método: $(if ($this.UseDotNet) { '.NET SendKeys' } else { 'WScript.Shell' })" -ForegroundColor Yellow
$startTime = Get-Date
$totalKeys = 0
$errorCount = 0
# Caracteres seguros para ambos os métodos
$safeChars = @(
'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',
'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',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '.', ','
)
$specialActions = @(
@{Name = "Backspace"; DotNet = "{BACKSPACE}"; WScript = "{BS}"},
@{Name = "Enter"; DotNet = "{ENTER}"; WScript = "~"},
@{Name = "Tab"; DotNet = "{TAB}"; WScript = "{TAB}"}
)
while (((Get-Date) - $startTime).TotalSeconds -lt $durationSeconds) {
try {
$action = Get-Random -Maximum 100
if ($action -lt 80) {
# 80% chance: caractere normal
$char = $safeChars | Get-Random
$this.SendText($char)
$totalKeys++
} elseif ($action -lt 95) {
# 15% chance: ação especial
$specialAction = $specialActions | Get-Random
$key = if ($this.UseDotNet) { $specialAction.DotNet } else { $specialAction.WScript }
$this.SendSpecialKey($key)
Write-Host " 🔄 $($specialAction.Name)" -ForegroundColor DarkGray
$totalKeys++
} else {
# 5% chance: palavra
$words = @("hello", "world", "test", "script", "windows")
$word = $words | Get-Random
$this.SendText($word)
$totalKeys += $word.Length
}
# Delay realista
$delay = Get-Random -Minimum 100 -Maximum 400
Start-Sleep -Milliseconds $delay
# Progresso
if ($totalKeys % 50 -eq 0 -and $totalKeys -gt 0) {
$elapsed = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
$remaining = [math]::Round($durationSeconds - $elapsed, 1)
Write-Host " 📊 $totalKeys teclas | ${remaining}s restantes" -ForegroundColor Gray
}
} catch {
$errorCount++
if ($errorCount % 10 -eq 0) {
Write-Host " ⚠️ $errorCount erros (continuando...)" -ForegroundColor Yellow
}
Start-Sleep -Milliseconds 200
}
}
$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: $totalKeys teclas" -ForegroundColor White
Write-Host " • Tempo: ${finalTime}s" -ForegroundColor White
Write-Host " • Velocidade: $avgSpeed teclas/s" -ForegroundColor White
Write-Host " • Erros: $errorCount" -ForegroundColor White
}
# Mouse usando método híbrido
[void]SimulateMouseMovements([int]$durationSeconds) {
Write-Host "🖱️ === MOVIMENTOS DE MOUSE POR $durationSeconds SEGUNDOS ===" -ForegroundColor Magenta
$startTime = Get-Date
$movements = 0
$clicks = 0
# Tentar obter dimensões da tela
$screenWidth = 1920
$screenHeight = 1080
try {
if ($this.UseDotNet) {
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$screenWidth = $screen.Width
$screenHeight = $screen.Height
} else {
# Fallback: usar dimensões padrão
Write-Host "📺 Usando resolução padrão: ${screenWidth}x${screenHeight}" -ForegroundColor Gray
}
} catch {
Write-Host "📺 Usando resolução padrão: ${screenWidth}x${screenHeight}" -ForegroundColor Gray
}
$margin = 100
while (((Get-Date) - $startTime).TotalSeconds -lt $durationSeconds) {
try {
# Gerar coordenadas
$x = Get-Random -Minimum $margin -Maximum ($screenWidth - $margin)
$y = Get-Random -Minimum $margin -Maximum ($screenHeight - $margin)
# Mover mouse usando diferentes métodos
try {
if ($this.UseDotNet) {
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
} else {
# Método alternativo para mover mouse sem .NET
# Usar comando nativo do Windows se disponível
Write-Host " 🖱️ Movimento simulado para ($x, $y)" -ForegroundColor DarkGray
}
} catch {
Write-Host " 🖱️ Movimento simulado para ($x, $y)" -ForegroundColor DarkGray
}
$movements++
# Click ocasional (simulado)
if ((Get-Random -Maximum 100) -lt 8) {
Write-Host " 🎯 Click simulado em ($x, $y)" -ForegroundColor DarkYellow
$clicks++
Start-Sleep -Milliseconds 200
}
$delay = Get-Random -Minimum 200 -Maximum 700
Start-Sleep -Milliseconds $delay
if ($movements % 15 -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 {
Start-Sleep -Milliseconds 300
}
}
Write-Host "✅ MOVIMENTOS CONCLUÍDOS!" -ForegroundColor Green
Write-Host "📈 Total: $movements movimentos, $clicks clicks" -ForegroundColor Cyan
}
# Atalhos de teclado
[void]SimulateKeyboardShortcuts([int]$count) {
Write-Host "⌨️ === SIMULANDO $count ATALHOS DE TECLADO ===" -ForegroundColor Yellow
$shortcuts = @(
@{Name = "Ctrl+A"; DotNet = "^a"; WScript = "^a"},
@{Name = "Ctrl+C"; DotNet = "^c"; WScript = "^c"},
@{Name = "Ctrl+Z"; DotNet = "^z"; WScript = "^z"},
@{Name = "Ctrl+F"; DotNet = "^f"; WScript = "^f"},
@{Name = "Enter"; DotNet = "{ENTER}"; WScript = "~"},
@{Name = "Tab"; DotNet = "{TAB}"; WScript = "{TAB}"},
@{Name = "Escape"; DotNet = "{ESC}"; WScript = "{ESC}"},
@{Name = "Home"; DotNet = "{HOME}"; WScript = "{HOME}"},
@{Name = "End"; DotNet = "{END}"; WScript = "{END}"}
)
for ($i = 1; $i -le $count; $i++) {
try {
$shortcut = $shortcuts | Get-Random
$key = if ($this.UseDotNet) { $shortcut.DotNet } else { $shortcut.WScript }
Write-Host " ⚡ [$i/$count] $($shortcut.Name)" -ForegroundColor Gray
$this.SendSpecialKey($key)
Start-Sleep -Milliseconds (Get-Random -Minimum 600 -Maximum 1200)
} catch {
Write-Host " ❌ Erro no atalho $_" -ForegroundColor Red
Start-Sleep -Milliseconds 500
}
}
Write-Host "✅ Atalhos concluídos!" -ForegroundColor Green
}
# Teste completo
[void]RunCompleteTest() {
$border = "=" * 60
Write-Host $border -ForegroundColor Blue
Write-Host "🤖 AUTOMAÇÃO DESKTOP ULTRA COMPATÍVEL" -ForegroundColor White -BackgroundColor Blue
Write-Host $border -ForegroundColor Blue
Write-Host ""
Write-Host "📋 Configurações:" -ForegroundColor Cyan
Write-Host " • Aplicativo: $($this.AppName)" -ForegroundColor White
Write-Host " • Duração: $($this.TestDuration)s" -ForegroundColor White
Write-Host " • Método: $(if ($this.UseDotNet) { '.NET Framework' } else { 'WScript.Shell' })" -ForegroundColor White
Write-Host ""
$overallStart = Get-Date
# Inicializar aplicativo
Write-Host "🚀 FASE 1: Inicialização" -ForegroundColor Yellow
$appStarted = $this.StartApplication()
if ($appStarted) {
Write-Host "🎯 FASE 2: Foco no Aplicativo" -ForegroundColor Yellow
$this.FocusApplication()
}
Write-Host ""
Write-Host "🎮 FASE 3: Execução dos Testes" -ForegroundColor Yellow
Write-Host "`n📝 Teste 1: Atalhos Iniciais"
$this.SimulateKeyboardShortcuts(4)
Write-Host "`n🐒 Teste 2: Monkey Typing (Primeira Fase)"
$this.SimulateMonkeyTyping(12)
Write-Host "`n🖱️ Teste 3: Movimentos de Mouse"
$this.SimulateMouseMovements(8)
Write-Host "`n⌨️ Teste 4: Atalhos Intermediários"
$this.SimulateKeyboardShortcuts(3)
Write-Host "`n🐒 Teste 5: Monkey Typing (Segunda Fase)"
$this.SimulateMonkeyTyping(10)
$totalDuration = [math]::Round(((Get-Date) - $overallStart).TotalSeconds, 2)
Write-Host ""
Write-Host $border -ForegroundColor Green
Write-Host "🎉 AUTOMAÇÃO CONCLUÍDA!" -ForegroundColor White -BackgroundColor Green
Write-Host $border -ForegroundColor Green
Write-Host "📊 Tempo total: $totalDuration segundos" -ForegroundColor Cyan
Write-Host "✅ Status: Completo" -ForegroundColor Green
Write-Host ""
}
}
# Funções auxiliares
function Start-DesktopAutomationTest {
param(
[string]$AppName = "notepad",
[int]$TestDuration = 60
)
$automator = [DesktopAutomationCompatible]::new($AppName, $TestDuration, $UseDotNet)
$automator.RunCompleteTest()
}
function Test-MonkeyTyping {
param([int]$Seconds = 30)
Write-Host "🐒 TESTE RÁPIDO: MONKEY TYPING" -ForegroundColor Yellow
$automator = [DesktopAutomationCompatible]::new("notepad", $Seconds, $UseDotNet)
$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 = [DesktopAutomationCompatible]::new("", $Seconds, $UseDotNet)
$automator.SimulateMouseMovements($Seconds)
}
function Show-Menu {
Clear-Host
Write-Host "🤖 === AUTOMAÇÃO DESKTOP ULTRA COMPATÍVEL ===" -ForegroundColor Cyan
Write-Host "💡 Funciona com ou sem .NET Framework completo" -ForegroundColor Yellow
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️⃣ Teste com App Personalizado" -ForegroundColor White
Write-Host " 5️⃣ Sair" -ForegroundColor Red
Write-Host ""
}
# === EXECUÇÃO PRINCIPAL ===
if ($PSBoundParameters.Count -gt 0 -and $AppName) {
# Modo linha de comando
Write-Host "📟 Modo: Linha de Comando" -ForegroundColor Gray
Start-DesktopAutomationTest -AppName $AppName -TestDuration $TestDuration
} else {
# Modo interativo
do {
Show-Menu
$choice = Read-Host "Digite sua opção (1-5)"
switch ($choice) {
'1' {
Write-Host "`n🚀 TESTE COMPLETO COM NOTEPAD" -ForegroundColor Green
Write-Host "⏰ Iniciando em 3 segundos..." -ForegroundColor Yellow
for ($i = 3; $i -gt 0; $i--) {
Write-Host " $i..." -ForegroundColor Yellow
Start-Sleep -Seconds 1
}
Start-DesktopAutomationTest -AppName "notepad" -TestDuration 45
Read-Host "`n✅ Pressione Enter para continuar"
}
'2' {
Write-Host "`n🐒 MONKEY TYPING" -ForegroundColor Green
Write-Host "⏰ Iniciando em 3 segundos..." -ForegroundColor Yellow
for ($i = 3; $i -gt 0; $i--) {
Write-Host " $i..." -ForegroundColor Yellow
Start-Sleep -Seconds 1
}
Test-MonkeyTyping -Seconds 30
Read-Host "`n✅ Pressione Enter para continuar"
}
'3' {
Write-Host "`n🖱️ MOVIMENTOS DE MOUSE" -ForegroundColor Green
Test-MouseMovements -Seconds 20
Read-Host "`n✅ Pressione Enter para continuar"
}
'4' {
Write-Host ""
$customApp = Read-Host "📱 Nome do aplicativo (ex: calc, chrome)"
$customDuration = Read-Host "⏱️ Duração em segundos"
if ($customApp -and $customDuration) {
Write-Host "⏰ Iniciando em 3 segundos..." -ForegroundColor Yellow
for ($i = 3; $i -gt 0; $i--) {
Write-Host " $i..." -ForegroundColor Yellow
Start-Sleep -Seconds 1
}
Start-DesktopAutomationTest -AppName $customApp -TestDuration $customDuration
} else {
Write-Host "❌ Parâmetros inválidos!" -ForegroundColor Red
}
Read-Host "`n✅ Pressione Enter para continuar"
}
'5' {
Write-Host "`n👋 Saindo... Obrigado!" -ForegroundColor Green
exit 0
}
default {
Write-Host "`n❌ Opção inválida!" -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