For those times when you just need to automate a UI without worrying about too many edge cases. SendKeys works well for simple applications where there isn’t a lot of choice required for workflow or lots of possible dialogs opening.
Start-Process notepad.exe Start-Sleep -Seconds 3 $Shell = New-Object -ComObject WScript.Shell $Shell.AppActivate('Untitled - Notepad') Start-Sleep -Seconds 3 $Shell.SendKeys('Hello World') # Close Notepad $Shell.SendKeys( % ) Start-Sleep -Seconds 1 $Shell.SendKeys( F ) Start-Sleep -Seconds 1 $Shell.SendKeys( X ) Start-Sleep -Seconds 1 # Answer No - Don't save when prompted $Shell.SendKeys( n ) Start-Sleep -Seconds 1
Note the code above is slightly incorrect. SendKeys can take a string or a single letter surrounded by curly braces to represent that key press. Unfortunately, the site is generated by Jekyll which doesn’t seem to like that syntax in the markup used for this post so I have had to omit it.
Occasionally, the shell implementation can get confused, in which case the alternative is to use a direct invokation of SendWait.
Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.SendKeys]::SendWait('Hello from SendKeys SendWait');