powershell,sendkey()和appactive()strangness

fal*_*lic 0 powershell

我有一个登录powershell脚本.作为脚本的一部分,它启动一个应用程序,然后等待4秒等待计算机赶上,然后发送一些按键.

$deviceID = "123xyz"
invoke-item ("C:\myapp")
...
$myshell = New-Object -com "Wscript.Shell"
start-sleep -s 4
$myshell.AppActivate("myapp");$myshell.sendkeys("1");$myshell.sendkeys("{TAB}");$myshell.sendkeys("$deviceID");$myshell.sendkeys("{ENTER}")
Run Code Online (Sandbox Code Playgroud)

除非用户在登录期间点击任何地方,否则它的效果很好.如果他们这样做,应用程序永远不会获得击键,应用程序在任务栏中闪烁.

看起来像AppActivate()似乎并没有真正起作用.有人对此有任何意见吗?

Kei*_*ill 7

您需要确保App是前台窗口.在PowerShell的社区扩展有一套-ForegroundWindow的cmdlet,可以在这方面帮助:

Add-Type -AssemblyName System.Windows.Forms
$proc = Get-Process notepad
Set-ForegroundWindow $proc.MainWindowHandle
Start-Sleep -Seconds 2 # Just so you can see the window before it closes :-)
[Windows.Forms.SendKeys]::SendWait('%{F4}')
Run Code Online (Sandbox Code Playgroud)

这是使用PowerShell V2的Add-Type cmdlet.另请注意,SendKeys在.NET中可用.