PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How do I send keys to an active window in Powershell?

 November 19, 2022     powershell, scripting     No comments   

Issue

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')

Solution

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')


Answered By - mklement0
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing