Home > Back-end >  How do I send keys to an active window in Powershell?
How do I send keys to an active window in Powershell?

Time:10-22

I want my script to open an application and send keys to it after it's opened. Currently, if I run the script, it opens the app but does not send the keys.

If I run just the send keys after the app has already been opened, it works.

Here is what I've got so far:

Start-Process -FilePath "C:\Program Files\VMware\VMware Horizon View Client\vmware-view.exe" -Wait -WindowStyle Normal

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('VMware')
Sleep 1
$wshell.SendKeys('~')
Sleep 3
$wshell.SendKeys('username')
Sleep 2
$wshell.SendKeys('{TAB}')
Sleep 1
$wshell.SendKeys('password')

CodePudding user response:

By using -Wait with Start-Process, you're blocking the call until the launched process terminates.

Thus, your attempts to send keystrokes will invariably fail, because they'll be sent after the target program has terminated.


Therefore:

  • Don't use -Wait

  • Use -PassThru, which makes Start-Process emit a process-information object representing the newly launched process, whose .ID property contains the PID (process ID).

  • For more reliable targeting, you can pass a PID to $wshell.AppActivate()

  • The general caveat applies: sending keystrokes, i.e. simulating user input is inherently unreliable.

$ps = Start-Process -PassThru -FilePath "C:\Program Files\VMware\VMware Horizon View Client\vmware-view.exe" -WindowStyle Normal

$wshell = New-Object -ComObject wscript.shell

# Wait until activating the target process succeeds.
# Note: You may want to implement a timeout here.
while (-not $wshell.AppActivate($ps.Id)) {
  Start-Sleep -MilliSeconds 200
}

$wshell.SendKeys('~')
Sleep 3
$wshell.SendKeys('username')
Sleep 2
$wshell.SendKeys('{TAB}')
Sleep 1
$wshell.SendKeys('password')
  • Related