(How to send keyboard input with PowerShell to any open window or application)
In this video I demonstrate a practical use case for using sendkeys in a PowerShell script. You can use sendkeys to automatically click a button, or confirm a prompt for instance.
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
[Microsoft.VisualBasic.Interaction]::AppActivate()
[System.Windows.Forms.SendKeys]::SendWait()
*powershell
*learn powershell
*automation
*learn automation
*windows
*windows powershell
*automatic installations
Code:
Demo1
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "notepad.exe"
start-sleep -Milliseconds 2500
[Microsoft.VisualBasic.Interaction]::AppActivate("Notepad")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("+{h}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{e}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{l}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{l}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{o}")
Demo2
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "notepad.exe"
Start-Sleep -Milliseconds 100
[Microsoft.VisualBasic.Interaction]::AppActivate("Notepad")
$line = "some line to write to notepad" #this can also come from a file or database
foreach ($c in $line.GetEnumerator()){
[System.Windows.Forms.SendKeys]::SendWait("{$c}")
Start-Sleep -Milliseconds 10
}
Demo3
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "mmc.exe" -ArgumentList "compmgmt.msc"
start-sleep -Milliseconds 2500
[Microsoft.VisualBasic.Interaction]::AppActivate("Computer Management")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 3}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{RIGHT 2}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 1}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{RIGHT 1}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 2}")
Demo4
add-type -AssemblyName microsoft.VisualBasic
Start-Process powershell.exe -ArgumentList "D:\__DEMOS\powershell-part57\installer-hangs.ps1" -Windowstyle Hidden
start-sleep -Milliseconds 5000
[Microsoft.VisualBasic.Interaction]::AppActivate("Yes or no")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Installer hangs script
Add-Type -AssemblyName System.Windows.Forms
$useip = [System.Windows.Forms.MessageBox]::Show("Do you want to provide a static IP?","Yes or no",4)
if ($useip -eq "Yes"){
#$ipnumber = Read-Host "enter last octect 1-255 is valid : $network_prefix"
}
Write-Output "and now we are done"
7 июл 2021